“设置精度”在分配的数字前的小数点后给出零 当我在C++中使用StEd精度(2)来尝试数字时,像“0.093”这样的数字会重新返回三,而不是十进制之后的两位数!我不明白这是为什么。我在下面包含了我最基本的代码,以防我严重遗漏了一些要点。谢谢 #include <iostream> #include <iomanip> using namespace std; int main() { double tax = 0.06 ; //Tax Rate float cost ; //Cost of item float computed ; //Non-rounded tax cout << "Enter the cost of the item: " ; cin >> cost ; computed = tax*cost; cout << "Computed: $" << computed << endl; cout << "Charged: $" << setprecision(2) << computed << endl; //Computed tax rounded to 2 decimal places return 0; } #包括 #包括 使用名称空间std; int main() { 双重税=0.06;//税率 浮动成本;//物料成本 已计算浮动;//非四舍五入税 成本; 计算=税收*成本; cout
这是因为“设置精度”在分配的数字前的小数点后给出零 当我在C++中使用StEd精度(2)来尝试数字时,像“0.093”这样的数字会重新返回三,而不是十进制之后的两位数!我不明白这是为什么。我在下面包含了我最基本的代码,以防我严重遗漏了一些要点。谢谢 #include <iostream> #include <iomanip> using namespace std; int main() { double tax = 0.06 ; //Tax Rate float cost ; //Cost of item float computed ; //Non-rounded tax cout << "Enter the cost of the item: " ; cin >> cost ; computed = tax*cost; cout << "Computed: $" << computed << endl; cout << "Charged: $" << setprecision(2) << computed << endl; //Computed tax rounded to 2 decimal places return 0; } #包括 #包括 使用名称空间std; int main() { 双重税=0.06;//税率 浮动成本;//物料成本 已计算浮动;//非四舍五入税 成本; 计算=税收*成本; cout,c++,C++,这是因为std::setprecision不设置小数点后的数字,而是设置有效(也称为“有意义”)数字,前提是不更改浮点格式以在小数点后使用固定数量的数字。要更改格式,必须在输出流中输入: cout << "Charged: $" << fixed << setprecision(2) << computed << endl; cout来自: 十进制精度决定了在表示浮点值的插入操作中要写入的最大位数。如何解释取决于是否将floatfie
std::setprecision
不设置小数点后的数字,而是设置有效(也称为“有意义”)数字,前提是不更改浮点格式以在小数点后使用固定数量的数字。要更改格式,必须在输出流中输入:
cout << "Charged: $" << fixed << setprecision(2) << computed << endl;
cout来自:
十进制精度决定了在表示浮点值的插入操作中要写入的最大位数。如何解释取决于是否将floatfield格式标志设置为特定的表示法。
在默认的浮点表示法中,精度字段指定小数点之前和之后的总计数中显示的最大有意义位数
在您的情况下:0.093
,93
-两个有意义的数字。根据,这要求2位精度(2位有效数字),而不是小数点后的2位。也许您应该查看。