How to print a very big value.

I am a newbie.
Please bear with my silly question please.
Why any one of this is not giving correct result??
1
2
3
4
5
6
7
8
#include <stdio.h>

int main() {
printf("%lf \n",(double)(60674*60674));
printf("%ld \n",(long)(60674*60674));
printf("%.1e \n",(60674*60674));
    return 0;
} 
60674 is a signed integer.
(60674*60674) is also a signed integer - the latter value requires more than the 31-bits of precision available (the remaining bit is used for the sign). The multiplication overflows the capacity of a signed integer and thus gives an incorrect result. Attempting to cast to another type afterwards is bolting the stable door after the horse has fled.

You might in this case squeeze it into an unsigned type which gives an extra bit of precision.

But it would probably be safer to use a floating-point type.
60674.0 is of type double and so is 60674.0*60674.0

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main() {
    
    printf("%u \n", 60674u*60674u);    // unsigned integer
    printf("%f \n", 60674.0*60674.0);  // double

    return 0;
    
}
Last edited on
From the compiler:

 In function 'int main()':
 4:31: warning: integer overflow in expression [-Woverflow] 
5:29: warning: integer overflow in expression [-Woverflow] 
6:24: warning: integer overflow in expression [-Woverflow] 
6:31: warning: format '%e' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]


So to fix that, you could either start with doubles in the first place, or cast the first number to a double.
Thank you for your quick reply.

it solved my problem.
Last edited on
But my program goes like this.
I guess it doesn't since that code won't compile. (also it would print the same value on each iteration of the loop).

change int neq;
to double neq;

or alternatively, change (double)(neq*neq);
to (double)neq * (double)neq;
Topic archived. No new replies allowed.