下面是我正在使用的一些简单代码:
#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";
}
我想让它打印 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";
}
然后你得到 1.000000
解释(编辑)
当您使用 std::fixed 时:
When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.
当您使用 std::defaultfloat (您正在使用的那个):
When floatfield is set to defaultfloat, floating-point values are written using the default notation: the representation uses as many meaningful digits as needed up to the stream's decimal precision (precision), counting both the digits before and after the decimal point (if any).
这就是为什么下面的 .000000
被认为是无关紧要的!
(如果你有 1.00001
它就会被打印出来)
关于c++ - 打印时缺少小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235336/