为什么此代码片段的答案是 400.002 而不仅仅是 400?
#include <iostream>
int main(){
using namespace std;
float a = 123.4;
a = (a - int(a))*1000;
cout << a << endl;
return 0;
}
我是新手。这是由于
float
的准确性,还是其他原因?如果我只想保留一位小数,我该怎么办?
浮点数是数学实数的粗略近似。它们并不代表确切的值。
因此,您可以使用极其精确的双精度浮点数。如代码片段所示:
#include<iostream>
using namespace std;
int main(){
double a = 123.4;
a = (a - int(a))*1000;
cout << a << endl; // Output 400
float a2 = 123.4;
a2 = (a2 - int(a2))*1000;
cout << a2 << endl; // Output 400.002
return 0;
}
欲了解更多,您可以参考以下链接: https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose- precision?view=msvc-170