我正在尝试创建一个C ++程序,该程序可以为客户计算营业税并显示收据。例如,如果您输入10作为第一笔销售金额,税率是0.0825,则总税额应显示为$ 0.83。为什么在收据末尾我的小计和应付款总额应该是10.83美元,却显示10.82美元?
//Customer Receipt
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
struct Item_Receipt
{
double item;
double cost;
double tax;
double subtotal;
};
int main()
{
vector <Item_Receipt> Store_Receipt;
Item_Receipt Purchase;
//Variables
const double item_tax = .0825;
double Item_Total = 0.0;
double Tax_Total = 0.0;
double Total_Sales = 0.0;
int numSales = 0;
cout << "First sales amount (Enter a 0 to stop): ";
cin >> Purchase.item;
Purchase.tax = Purchase.item * item_tax;
Purchase.subtotal = Purchase.item + Purchase.tax;
Store_Receipt.push_back(Purchase);
Item_Total += Purchase.item;
Tax_Total += Purchase.tax;
Total_Sales += Purchase.subtotal;
numSales++;
while (Purchase.item > 0.0)
{
cout << "Next sales amount (Enter a 0 to stop): ";
cin >> Purchase.item;
if(Purchase.item > 0.0)
{
Purchase.tax = Purchase.item * item_tax;
Purchase.subtotal = Purchase.item + Purchase.tax;
Store_Receipt.push_back(Purchase);
Item_Total += Purchase.item;
Tax_Total += Purchase.tax;
Total_Sales += Purchase.subtotal;
numSales++;
}
else
cout << endl << "That was the last item being puchased.\nHere is your itemized receipt." << endl << endl;
}
//end while
//Output
cout << "----------------------------------------- " << endl;
cout << "\tReceipt of Purchase" << endl;
cout << "----------------------------------------- " << endl << endl;
cout << fixed << setprecision(2);
cout << setw(10) << "Item Cost" <<
setw(15) << "Item Tax" <<
setw(15) << "Subtotal" << '\n';
cout << "----------------------------------------- " << endl;
for(int x=0;x<numSales;x++)
cout << setw(8) << Store_Receipt[x].item << setw(15) << Store_Receipt[x].tax <<
setw(15) << Store_Receipt[x].subtotal << endl;
cout << "----------------------------------------- " << endl;
cout << setw(10) << "Item Total" <<
setw(15) << "Tax Total" <<
setw(15) << "Total Due" << endl;
cout << setw(8) << Item_Total << setw(15) << Tax_Total <<
setw(15) << Total_Sales << endl;
cout << "----------------------------------------- " << endl;
cout << "\tYou purchased " << numSales << " items." << endl;
cout << "----------------------------------------- " << endl;
cout << "\tThank you! Have a nice day!" << endl;
cout << "----------------------------------------- " << endl;
cin >> numSales;
return 0;
}
答案 0 :(得分:3)
setprecision(2)
的含义不是“舍入到两位小数”,而是“显示两位小数”。实际值为10.825,但您只显示前两位十进制数字。
如果要舍弃中点,则需要在结果上使用one of the rounding functions。
由于要四舍五入到小数点后第二位,因此必须首先将数字乘以100,然后将其四舍五入,然后再除以100。可以在函数的帮助下完成此操作:
double round_to_cents(double v) {
return std::round(v * 100) / 100;
}
然后四舍五入计算税款:
Purchase.tax = round_to_cents(Purchase.item * item_tax);
(Demo)