你如何在数字上添加 2 位小数

How do you add 2 decimal places to numbers?

本文关键字:小数 添加 数字上      更新时间:2023-10-16

这是我的代码。我的教授给我们的信息只显示小数点 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 的次数,结果为非零。