Simple question C

I was born in the modern world, so I often have to deal with similar things, but someone can explain how to get the correct number in the following code. Here is one attempt by many:

#define X 2527 #define Y 2463 #define Z 3072 main() { long int c = X*Y*Z; printf("%ld",c); } 

I'm just trying to print a long integer, but it always prints the wrong result. I get whole overflows - if so, how can I prevent them? Or is it my choice of printf format?

+4
source share
4 answers

Overflow is fine because you are trying to write a 32-bit number to a 32-bit variable ( long int ).

Use long long int and %lld in the format string.

 #define X 2527LL #define Y 2463LL #define Z 3072LL main() { long long int c = X*Y*Z; printf("%lld",c); } 
+7
source

The problem is that constants are not interpreted as long integers, and casting to a long integer occurs only after evaluating the expression. You can use them in an expression to solve this or simply define them as long constants. In addition, a long time may not be enough; a long time should be used if supported.

+2
source

Yes, you are overflowing. The answer does not fit into a 32-bit signed integer that is longer than int. You should use the 64 bit type, which is long.

In addition, you must perform type casting, otherwise the intermediate calculation will overflow.

 #define X 2527 #define Y 2463 #define Z 3072 main() { long long c = (long long)X*Y*Z; printf("%lld",c); } 
+1
source
 #define X 2527.0 #define Y 2463 #define Z 3072 main() { double c = X*Y*Z; printf("%lf",c); } 

you can also use double.

0
source

All Articles