我想爲學校創建一個「簡單的收銀機」程序。該計劃應詢問用戶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