我想为学校创建一个“简单的收银机”程序。该计划应询问用户5个购买金额,对购买金额应用固定税率,然后显示小计。这里是我的代码:我将如何着手在我的程序中创建计算?
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
/*
*
*/
int main(int argc, char** argv)
{
// Declare and initialize necessary variables
// You need to use floats for these
const float TAXRATE = 0.07; // 7% tax rate
float item1 = 0.0, item2 = 0.0, item3 = 0.0, item4 = 0.0, item5 = 0.0;
float subTotal = 0.0, taxTotal = 0.0, totalDue = 0.0;
float itemPurchases[5];
// Take 5 items as input
// Get item amounts from user
for (int i =0; i < 5; i++)
{
cout << "Please enter a purchased item" <<endl;
cin >> itemPurchases[i];
}
// Calculate subTotal, taxTotal, and totalDue
subTotal = itemPurchases[5];
taxTotal = subTotal * TAXRATE;
totalDue = subTotal + taxTotal;
// Drop down two lines on the output and print receipt header
cout << "\n" << endl;
cout << "Here is your receipt\n" << endl;
// Output the items
cout << fixed << setprecision(2); // Make sure all numbers have 2 decimals
cout << setw(15) << "Item 1 costs: $" << setw(10) << right << item1 << endl;
cout << setw(15) << "Item 2 costs: $" << setw(10) << right << item2 << endl;
cout << setw(15) << "Item 3 costs: $" << setw(10) << right << item3 << endl;
cout << setw(15) << "Item 4 costs: $" << setw(10) << right << item4 << endl;
cout << setw(15) << "Item 5 costs: $" << setw(10) << right << item5 << endl;
// Output single separation line
cout << "----------------------------" << endl;
// Output subTotals
cout << setw(15) << right << "Subtotal: $" << setw(10) << right << subTotal << endl;
cout << setw(15) << right << "Tax Total: $" << setw(10) << right << taxTotal << endl;
// Output double separation line
cout << "==========================" << endl;
cout << setw(15) << right << "Total Due: $" << setw(10) << right << totalDue << endl;
// End of program
return 0;
}
当我运行该程序,这是我得到什么:
Please enter a purchased item
5.00
Please enter a purchased item
6.00
Please enter a purchased item
7.00
Please enter a purchased item
8.00
Please enter a purchased item
9.00
Here is your receipt
Item 1 costs: $ 0.00
Item 2 costs: $ 0.00
Item 3 costs: $ 0.00
Item 4 costs: $ 0.00
Item 5 costs: $ 0.00
----------------------------
Subtotal: $ 0.00
Tax Total: $ 0.00
==========================
Total Due: $ 0.00
我的问题是我应该添加到程序的实际人数达将改为显示的0.00 ?
您应该添加代码,用于计算来自特定itemPurchases(如评论所述)的subTotal金额。 subTotal = itemPurchases [5]只是错误的,因为您正在索引超出范围(索引从0开始)。 你应该做的是注意你的课堂并做好功课。 –
如果你的代码不起作用,你不知道为什么,*尝试更简单*。尝试编写接受一个值并显示它的代码;那么也许你会在上面的代码中看到,你正在将值读入一组变量,并打印另一组变量的内容。 – Beta