使用cout打印小数点后的X数
print X number after the decimal point using the cout
我有这样的代码:
double a = 7.456789;
cout.unsetf(ios::floatfield);
cout.precision(5);
cout << a;
还有这个
double a = 798456.6;
cout.unsetf(ios::floatfield);
cout.precision(5);
cout << a;
第一个代码的结果是:7.4568这几乎是我想要的(我想要的是7.4567)第二题的结果是7.9846e+05这根本不是我想要的(我想要)我想打印这个数字,直到小数点后4位
通过使用unsetf()
,您告诉cout
使用其默认的浮点值格式。由于您想要小数之后的精确位数,您应该使用setf(fixed)
或std::fixed
来代替,例如:
double a = ...;
std::cout.setf(std::fixed, ios::floatfield);
std::cout.precision(5);
std::cout << a;
.
double a = ...;
std::cout.precision(5);
std::cout << std::fixed << a;
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 用c++把小数点转换成八进制
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- GCC 4.8.2 自动矢量化由于 cout 而失败
- std::cout输出int时出现编译错误
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- C++ Setter/Getter,cout 工作,printf 失败
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 使用 cin 时接受小数点后的 2 位数字
- 结构元素名称要 cout?
- 使用模板类重载 cout
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- C++ cout 列表,其中小数点使用 setw(x) 对齐,而不是put_money
- 使用cout打印小数点后的X数