在很长一段时间没有编程之后,我正在为下个月的作业而忙于 C++。我了解到变量可以溢出:具体来说,float 类型的变量不会像 double 类型那样保存那么多的小数。但是,我尝试了这段代码:
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
cout << setprecision(20);
double t(0.1);
float g(0.1);
cout << t << endl;
cout << g << endl;
static_cast<float>(t);
cout << t << endl;
}
而且,令我惊讶的是,第一个和最后一个(double t 和 float t)的精度相同,而 float g 的精度更低。这对我来说似乎有点违反直觉,static_cast 如何保持数字的精度?
非常感谢。
最佳答案
那是因为你没有为任何东西分配 static_cast
ed 值:
#include <iostream>
#include <iomanip>
int main() {
using namespace std;
cout << setprecision(20);
double t(0.1);
float g(0.1);
cout << t << endl;
cout << g << endl;
g = static_cast<float>(t); // There was no assignment in your code
cout << g << endl;
}
现在输出:
0.10000000000000000555
0.10000000149011611938
0.10000000149011611938
关于c++ - 静态转换如何在 C++ 中保持数字的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38044785/