Array with large numbers

Asked

Viewed 96 times

0

This program stores 5 numbers in array and then displays them, but imagining that I want to save large numbers as:

8.12415367228151 / 119.038571952966 / 169.873349402464 / 324.997128488111 / -283.262126034417

What modification can I make for the program to store numbers of this size but also to store smaller numbers like: 20/30/40/-50/-60

I’ve tried to change the int values[5] for long int value [5] and for other types of data types but I get nowhere.

    #include <stdio.h>
    #include <stdlib.h>
    int main() {
        int values[5];
        printf("Enter 5 integers: ");
        for (int i = 0; i < 5; ++i) {
            scanf_s(" %d", &values[i]);
        }
        printf("Displaying integers: ");
        for (int i = 0; i < 5; ++i) {
            printf("%d\n", values[i]);
        }
        system("pause");
        return 0;
    }
  • 1

    See <Limits> for the minimum and maximum limits of the values that can be stored in the various types of data.

  • 1

    If you want to work with arbitrary precision numbers use a specific library, such as GMP - The GNU Multiple Precision Arithmetic Library [https://gmplib.org/].

2 answers

1

Do with long long int value[] and scanf("%lli", value[i]);

I don’t know if these numbers you showed are integer, because you put a dot, so if they’re not put a long double

0


You have marked this code with the C++ tag, but it is visible that it is in C.

I was in doubt if this example of large numbers is an integer or double, but since the array is int I will assume that it is integer.

Variables can store any value as long as the value is within their range, so you don’t need to modify anything, just choose the correct type.

You said you changed the type of int to long int, but you also need to change the reading and writing specifications from %d to %Ld.

I made an example here using the type int64_t defined in the stdint header. h, this guy can store very large numbers, and I only used functions present in the standard C library to maintain portability.

#include <stdio.h>
#include <stdint.h>

int main() {
  const int vSize = 5;

  int64_t values[vSize];

  printf("Digite %d números inteiros\n", vSize);

  for(int i = 0; i < vSize; ++i) {
    printf("%d: ", (i + 1));
    scanf("%ld", &values[i]);
  }

  printf("Exibindo os números\n");

  for(int i = 0; i < vSize; ++i) {
    printf("%d: %ld\n", (i + 1), values[i]);
  }

  return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.