下面是从网上搜集到的几个关于浮点数的例子,结果可能会因为操作系统和编译器的不同而不同。我的平台是Linux 64位,gcc版本是4.4.7,编译时使用默认选项 。
int x = 0.58 * 100;
printf("%d",x); //57,not 58
printf("%d",0.1 + 0.2 == 0.3); //0,not 1
printf("%fn",3.14f + 1e10f - 1e10f); //0.0,not 3.14
printf("%fn",3.14f + (1e10f - 1e10f)); //3.14
float d1, d2, d3, d4;
d1 = 194268.02f;
d2 = 194268f;
d4 = 0.02f;
d3 = d1 - d2;
if (d3 > d4)
printf(">0.02n");
else if (d3 < d4)
printf("<0.02n"); //true
else
printf("=0.02n"); //false
printf("%f - %f = %f n", d1,d2,d3); //194268.015625 - 194268.000000 = 0.015625,not 194268.02 - 194268 = 0.02
把float换成double
double d1, d2, d3, d4;
d1 = 194268.02;
d2 = 194268;
d4 = 0.02;
d3 = d1 - d2;
if (d3 > d4)
printf(">0.02n");
else if (d3 < d4)
printf("<0.02n"); //true
else
printf("=0.02n"); //false
printf("%f - %f = %f n", d1,d2,d3); //194268.020000 - 194268.000000 = 0.020000
gcc compare.c -o compare.o
float p3x = 80838.0f;
float p2y = -2499.0f;
double v321 = p3x * p2y;
printf("%f",v321); //-202014160,not -202014162