你如何在数字上添加 2 位小数
How do you add 2 decimal places to numbers?
这是我的代码。我的教授给我们的信息只显示小数点 2 位是 out.precision(2) ;.
cout << "Welcome to the Book Store" << endl << endl;
cout << "Enter the single copy price: $" ;
cin >> single_copy_price ;
cout << "Enter the number of books sold: " ;
cin >> num_of_books_sold ;
cout << "Enter the discount percentage: " ;
cin >> discount_percentage ;
cout << "********************************************" << endl ;
subtotal = single_copy_price * num_of_books_sold ;
cout.precision(2) ;
cout<< "Subtotal: $" << subtotal << endl ;
cout << "Discount percentage: " << discount_percentage << "%" << endl ;
discount_ammount = subtotal * (discount_percentage / 100) ;
cout.precision(2) ;
cout << "Discount ammount: $ " << discount_ammount << endl ;
cout.precision(2) ;
cout << "Final price: $" << subtotal - discount_ammount << endl ;
return 0;
'
但是,这是我的结果:
欢迎来到书店
输入单份价格: $10.50输入售出书籍数量:20输入折扣百分比:15
小计:$2.1e+02折扣百分比: 15%折扣:$ 32最终价格:$1.8e+02程序以退出代码结束:0
谢谢你的帮助!
问题是cout.setprecision(2)
. 它的作用是限制显示的数字中有效数字的数量。 它对科学工作很有用,但不是你要找的。
一个人的解决方案是编写自己的格式化方法:http://www.arachnoid.com/cpptutor/student3.html
最后是第6点,货币。 他的解决方案还以 $ 和逗号格式表示数千位。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void showCurrency(double dv, int width = 14)
{
const string radix = ".";
const string thousands = ",";
const string unit = "$";
unsigned long v = (unsigned long) ((dv * 100.0) + .5);
string fmt,digit;
int i = -2;
do {
if(i == 0) {
fmt = radix + fmt;
}
if((i > 0) && (!(i % 3))) {
fmt = thousands + fmt;
}
digit = (v % 10) + '0';
fmt = digit + fmt;
v /= 10;
i++;
}
while((v) || (i < 1));
cout << unit << setw(width) << fmt.c_str() << endl;
}
最简单的解决方案是将精度设置为比整数部分中的位数多 2。 要弄清楚这一点,请转换为 int 并计算您可以除以 10 的次数,结果为非零。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- C++将浮点指针值舍入为小数位数
- 从给定的 I 和 D 序列中形成最小数
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- 为什么我必须添加一个小数才能在C++中正确计算此数学
- C 如何在小数系统中添加两个数字
- 如何在不破坏当前工作代码的情况下添加小数
- 你如何在数字上添加 2 位小数