-2

In C, is it possible to do the below operation without causing an integer overflow? My answer needs to be an integer which I use later on in the program. The code prints -337. The correct answer should be 2014.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
   int i;
   i = (10000 * 735625 + 14780)/3652425;
   printf("%d",i);
   return 0;
}
Blue Ice
  • 7,888
  • 6
  • 32
  • 52
  • 2
    Try to use `long long` instead. – herohuyongtao Mar 09 '14 at 17:21
  • 4
    Any reason why you use such a strange formula if you know the result already? – deviantfan Mar 09 '14 at 17:22
  • 2
    Just change `10000` to `10000LL` and you should be set. That changes the calculation to use `long long`, which has higher precision. The result will (in this case) still fit in a regular `int`. – Joachim Isaksson Mar 09 '14 at 17:28
  • Thanks Joachim. You were spot on. – user3398879 Mar 10 '14 at 00:04
  • Thanks Joachim. You were spot on. And in answer to your question deviantfan, one of the numbers in the formula :735625 is a calculated variable g in my program. It served no purpose to write out my whole programe here. You only need an instance of the variable. – user3398879 Mar 10 '14 at 00:15

2 Answers2

1

Based on usual arithmetic conversions, it will overflow as 10000 * 735625 + 14780 (out of int's range) is trying to save into int.

Integral promotions are performed on the operands as follows:

  • If either operand is of type unsigned long, the other operand is converted to type unsigned long.
  • If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
  • If the preceding two conditions are not met, and if either operand is of type long, the other operand is converted to type long.
  • If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.
  • If none of the preceding conditions are met, both operands are converted to type int.

To work out, you need to use long long (with larger range) stead.

A simple way, as @JoachimIsaksson suggested, is to put LL after 10000 to calculate with long long's precision:

i = ( 10000LL * 735625 + 14780)/3652425;

See it live: http://ideone.com/pA2Pvm

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • Also make sure you change the `printf` specifier from `%d` - [How to print 'long long int' in C?](http://stackoverflow.com/questions/13590735/printf-long-long-int-in-c-with-gcc) – Bert Mar 09 '14 at 17:27
0
i = (int)((10000.0 * 735625.0 + 14780.0)/3652425.0);

printf("%d",i);

valter