下面是我正在使用的一些简单代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 1.66f;
int d = (int)f;
double g = (double)d;
cout.precision(6);
cout<<g<<"\n";
}
Run Code Online (Sandbox Code Playgroud)
我想要它打印,1.000000但它只打印1.但是,即使将int升级为double后,它是否会自动将其转换为整数值?
你可以加 cout << std::fixed;
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 1.66f;
int d = (int)f;
double g = (double)d;
cout.precision(6);
cout << std::fixed;
cout<<g<<"\n";
}
Run Code Online (Sandbox Code Playgroud)
你明白了 1.000000
解释(编辑)
当你使用std :: fixed时:
当floatfield设置为fixed时,使用定点表示法写入浮点值:该值用精确字段 (精度)指定的小数部分中的数字精确表示,并且没有指数部分.
当您使用std :: defaultfloat(您正在使用的那个)时:
当floatfield设置为defaultfloat时,使用默认表示法写入浮点值:表示根据需要使用尽可能多的有意义数字,直到流的小数精度(精度),计算小数点前后的数字(如果有的话) ).
这就是为什么以下.000000被认为是无关紧要的!
(如果你有1.00001它会被打印)