Today, I found some strange calculations which is not known to me (Also didn't find any issues in SO regarding this) regarding pow()
function of math.h
in C.
The code I was experimenting was:
#include <stdio.h>
#include <math.h>
int main(){
//1st case
long long result = pow(2, 63);
printf("1st case: %lld\n", result);
//2nd case
result = pow(2, 64);
printf("2nd case: %lld\n", result);
//3rd case
printf("3rd case: %lld\n", (long long) (pow(2, 64)/12000));
//4th case
result = pow(2, 64);
result = result/12000;
printf("4th case: %lld\n", result);
//5th case
result = pow(2, 64) / 12000;
printf("5th case: %lld\n", result);
return 0;
}
The output was:
1st case: 9223372036854775807
2nd case: 9223372036854775807
3rd case: 1537228672809129
4th case: 768614336404564
5th case: 1537228672809129
I have several questions which I am not clear about. I am using CodeBlocks 16.01 IDE and GNU GCC Compiler.
1. In first case, the output is, 2^63 = 9223372036854775807
. Why is that so? The last digit is odd here. It is supposed to be 9223372036854775808
.
2. In 2nd case, 2^64 = 9223372036854775807
, which is the same as previously calculated 2^63
(actually this is the same for any value of exponent greater than 63). Yes, I understand that there overflow occurs for long long int
data type. But why the wrong value is assigned?
3. In 3rd case and 5th case (Actually identical), the answer is correct. But in the 4th case, there is wrong answer. According to arithmetic operations, the mathematical operations in 4th case should be identical with the rest two but it is actually not. Then where is the differences?