使用cout打印小数点后的X数

print X number after the decimal point using the cout

本文关键字:小数点 cout 打印 使用      更新时间:2023-10-16

我有这样的代码:

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;