# 关于【深基】习题2-4的问题

@shellee 2021-05-03 20:26 回复

## 【深基】习题2.4原题：

#include<cstdio>
using namespace std;
int main(){
float a=0.1;
printf("%d",int(2-a*a*100));
//printf("%.10f",2-a*a*100);
return 0;
}

#include<cstdio>
using namespace std;
int main(){
float a=0.1;
printf("%d\n",int(2-a*a*100));
printf("%d\n",int(a*a*100));
printf("%.10f\n",a*a*100);
printf("%.10f\n",2-a*a*100);
printf("%f\n",2-a*a*100);
printf("%f\n",a*a*100);
return 0;
}

0
1
1.0000001192
0.9999998808
1.000000
1.000000


@andyli  2021-05-03 20:35 回复 举报

1. 二进制无法准确表示十进制数据
2. 保存浮点数的精度有限

@shellee 2021-05-03 20:58 回复 举报

@andyli @zhaoyp 感谢回答问题。 看到@zhaoyp 的回答，我运行了下面的代码。

#include<cstdio>
using namespace std;
int main(){
float a=0.1;
double b=0.1;
printf("%d\n",int(2-a*a*100));
printf("%d\n",int(a*a*100));
printf("%.10f\n",a*a*100);
printf("%.10f\n",2-a*a*100);
printf("%f\n",2-a*a*100);
printf("%f\n",a*a*100);
printf("%d\n",int(2-b*b*100));
printf("%d\n",int(b*b*100));
printf("%.10f\n",b*b*100);
printf("%.10f\n",2-b*b*100);
printf("%f\n",2-b*b*100);
printf("%f\n",b*b*100);
return 0;
}

0
1
1.0000001192
0.9999998808
1.000000
1.000000
0
1
1.0000000000
1.0000000000
1.000000
1.000000


 printf("%d\n",int(2-b*b*100));

@zhaoyp  2021-05-03 21:23 回复 举报

printf("%d\n",2-int(b*b*100));