如何在C++中正确设置双精度
How to properly set precision for doubles in C++
我正在做一个项目,我需要做一些数学运算并为用户提供带有美元的输出,所以我想让我的控制台告诉用户一个像$20.15
而不是$20.153
这样的答案。我使用了设置精度函数: cout << setprecision(2);
,但是数字并没有成为我想要的样子,而是将它们转换为科学记数法。
我输出了很多数字,所以拥有像 setprecision
这样的函数最适合我,以便于使用。
如何正确显示仅显示两个小数位的数字,而不让控制台以科学记数法给我数字?
谢谢
内森
编辑:
这是我的代码中我遇到问题的部分:
int main() {
cout << setprecision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
显然还有更多,但这是我需要帮助的。
要解决此问题,您应该对 cout 使用固定的浮点表示法。您可以在此处找到更多信息。
尝试将cout << fixed
添加到代码中,如下面的代码所示。若要将精度设置为 2
,可以使用 precision
属性。
cout << fixed;
cout.precision(2);
以下是完整的代码:
using namespace std;
int main() {
cout << fixed;
cout.precision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
}
Iostreams是格式化浮点值的痛苦。但是,为什么要使用浮点来表示货币值呢?您应该存储整数便士(或十分之一便士),因为尽管您不是以整数美元来衡量,但您的值实际上是固定点的。而且你真的不需要浮点带来的麻烦。然后,您可以将值的全部和"部分"部分分别流式传输"(使用 /
和 %
!),作为整数,中间有一个'.'
。
同时,请尝试std::fixed
.
作
弊,看着纯粹主义者发疯......
double time; //Only want two decimal places.
double timeCon = time * 100.0; //Pull out the two decimals I want.
int timeCut = timeCon; //Cut all decimal values.
double timeRevert = timeCut / 100.0; //Laugh.
cout << timeRevert << endl; //Watch heads explode.
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 将双精度变量设置为另一个变量的值
- 位设置为浮点数或双精度值 c++
- 保证最大输出长度为双精度,并设置默认输出格式的精度
- 使用词法强制转换在'string to double'中设置双精度变量的精度
- 无法获得固定的设置精度双精度以显示小数位
- 在不使用流(ios_base::precision)的情况下设置双精度
- 将双精度值的格式设置为小数点后 1 位
- 如何在C++中使用双精度/浮点类型时设置精度
- 如何在C++中正确设置双精度
- 使用 fstream 设置精度以输出文件 - 格式为双精度
- 如何通过 JNI 设置 java 类的双精度/整数类型的值
- vc.net:无法设置双精度变量的值
- 在 AT&T 内联装配体中将浮点/双精度设置为常量值