C语言运算时类型自动转换及精度损失问题
#include<stdio.h>
#include<math.h>
int main(){
unsigned long long a=0;
int i;
for(i=0;i<64;i++){
a+=pow(2,i);
}
unsigned long long b=a/25000;
printf("%llu\n",a);
printf("%llu",b);
return 0;
}
/*
a: 0
b: 0
*/
#include <stdio.h>
#include <math.h>
int main() {
unsigned long long a = 0;
int i;
for(i = 0; i < 64; i++) {
double temp = pow(2, i);
if(i == 63) {
printf("temp: %lf\n", temp);
printf("a: %llu\n", a);
unsigned long long s = a + temp;
printf("s: %llu\n", s);
}
a += temp;
}
unsigned long long b = a / 25000;
printf("%llu\n", a);
printf("%llu\n", b);
return 0;
}
/*
temp: 9223372036854775808.000000
a: 9223372036854775808
s: 0
*/
9223372036854775808 + 9223372036854775808 = 18446744073709551616
18446744073709551616 已经超过了 unsigned long long 能表示的范围,加法溢出了
#include<stdio.h>
#include<math.h>
int main(){
unsigned long long a=0;
int i;
for(i=0;i<63;i++){
a+=(unsigned long long)pow(2,i);//没有进行强制类型转换,则该步的加法转成double类型进行相加,结果失真。
}
unsigned long long b=a/25000;
printf("%llu\n",a);
printf("%llu",b);
return 0;
}