0

This is just a test C program that I want it to calculate the product of 13 digits

#include <stdio.h>
#include <stdlib.h>
int main ()
{
    long prod; 
    prod = 5*5*7*6*6*8*9*6*6*4*8*9*5;
    printf ("%ld\n", prod);
    system("pause");
    return 0;
}

but it just says

[Warning] integer overflow in expression [-Woverflow]

The program runs but it displays a very different product value than the real one... I tried to change the int and the long int to float and double and not sure what to do next.

  • What compiler are you using? What does sizeof(long) and sizeof(long long) give you? – brothir Jan 14 '19 at 02:40
  • See also [Why write 1,000,000,000 as 1000*1000*1000 in C?](https://stackoverflow.com/q/40633059/2410359) and [There are reasons not to use 1000 * 1000 * 1000.](https://stackoverflow.com/a/40637622/2410359) – chux - Reinstate Monica Jan 14 '19 at 02:48
  • 1
    **If** you're using a 64 bit machine, `long` is the same size as `long long` [usually, for posix OSes: linux, BSD, macOS--the exception is WinX]. So, if you changed `5*5*...` into `5lu*5*...` it should produce the same answer as Jerry's below. That change forces the rvalue calculations to be done with `long` instead of `int` (i.e.) the lvalue `prod` does _not_ influence the size of the `rvalue`--the conversion is done _after_ the calculations. But, using `long long` is the safer bet for all architectures/systems. – Craig Estey Jan 14 '19 at 03:33

1 Answers1

4

Changing the type of the result won't help in a case like this.

The problem is that since all the input values are ints, only int sized multiplication is ever done (then, if you assign that to a double or whatever, the result is converted to double--but only after it has overflowed.

If you start with a larger type, then the multiplication will be done with that larger type:

#include <stdio.h>
#include <stdlib.h>
int main ()
{
    unsigned long long prod; 
    prod = 5ull*5*7*6*6*8*9*6*6*4*8*9*5;
    printf ("%llu\n", prod);
    system("pause");
    return 0;
}
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111