-2

So I have some code to get some large numbers, and I am storing them in long, but the output is still not correct because I get negative numbers.

Here is my code:

int user_want =0;
long answer=1;
int loop = 0;
printf("What is required?");
scanf("%d", &user_want);
for(loop=1;loop<=user_want; loop++){
  answer = answer*loop
  printf("%ld\n", answer)
}

I get this output:

enter image description here

Pls help!

Albert
  • 13
  • 4
  • Does this answer your question? [Multiplication of two integers in C++](https://stackoverflow.com/questions/31662792/multiplication-of-two-integers-in-c) – Random Davis Feb 16 '21 at 19:33
  • See [integer limits](https://learn.microsoft.com/en-us/cpp/c-language/cpp-integer-limits?view=msvc-160). – jarmod Feb 16 '21 at 19:33
  • What is the value of `LONG_MAX` on your system? – Andrew Henle Feb 16 '21 at 19:33
  • Use a `long long` if you want that value. – Dock Feb 16 '21 at 19:35
  • @RandomDavis Probably better: https://stackoverflow.com/questions/19230573/cannot-calculate-factorials-bigger-than-20-how-to-do-so The values are different because the integer type used is `unsigned long long`, but the underlying cause is the same. – Andrew Henle Feb 16 '21 at 19:35
  • @AndrewHenle, I don't know how to check – Albert Feb 16 '21 at 19:38
  • @Dock I tried that, it didn't work – Albert Feb 16 '21 at 19:38
  • @Albert [Integer limits are defined in the `limits.h` file](https://port70.net/~nsz/c/c11/n1570.html#7.10). So if you `#include `, you could then do something like `printf( "LONG_MAX: %ld\n", LONG_MAX );` – Andrew Henle Feb 16 '21 at 19:40
  • Ok @AndrewHenle I wil try this, it comes out as `2147483647`, this is clearly smaller than what is needed. What should I do? – Albert Feb 16 '21 at 20:26
  • This code contains a syntax error and will fail to compile. Please copy and paste your exact code; after reading these guidelines: https://stackoverflow.com/help/minimal-reproducible-example – M.M Feb 16 '21 at 20:33

1 Answers1

0

On most platforms long is the same as int. You need to use long long which uses more bytes (again, on most platforms :-) ). You can print out sizeof(int), sizeof(long), etc. to see how many bytes they use on your platform. BTW, the numbers you get is simply the result of overflow in the computation.

LaszloLadanyi
  • 973
  • 4
  • 12
  • I tried `long long` but it didn't work either – Albert Feb 16 '21 at 19:39
  • 1
    It is going to be correct a bit longer than using just long. If you want it to be correct "forever" then you need to use an infinite precision library, like gmp (https://gmplib.org/). – LaszloLadanyi Feb 16 '21 at 19:41
  • 1
    I doubt the claim that most platforms have `long` the same size as `int` . LP64 is very common across desktops and embedded devices now. LP32 (16-bit int) also was popular in the past – M.M Feb 16 '21 at 20:36