4件の観光名所するために必要な、このコード「ながら」でアキュムレータをクリア:C++ - ループ
- が販売アイテム
- の数は、税金の割合を入力し、各販売アイテム
- の価格を入力してください
- 再び
を実行するためのオプション私は、これらすべての要件を完了しているが、コードが繰り返されたときに、私の唯一の問題はでています。私はテスト後のループの中でアキュムレータに総項目値を保存します。プログラムがループすると、アキュムレータがクリアされず、古い値の上に新しい値が追加され続けます。あなたが必要とする
(例:コードの私の最初の走行は20 $の合計を持っていた、と繰り返し実行が30 $の合計を持って、それは50 $であること、私の合計金額が表示されます)
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
char answer = ' ';
int saleItems = 0;
double itemValue = 0.0;
double titemValue = 0.0;
double taxPerc = 0.0;
do {
cout << "How many sales items do you have? : ";
cin >> saleItems;
for (int x = 1; x <= saleItems; x += 1){
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue;
}
cout << endl << endl;
cout << "Enter in the sales tax percentage(Enter 10 for 10%): ";
cin >> taxPerc;
cout << endl << endl;
double saleTax = titemValue * (taxPerc/100);
double grandTotal = titemValue + saleTax;
cout << fixed << setprecision(2);
cout << "********************************************" << endl;
cout << "******** S A L E S R E C E I P T ********" << endl;
cout << "********************************************" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** Total Sales $" << setw(9) << titemValue << " **" << endl;
cout << "** Sales Tax $" << setw(9) << saleTax << " **" << endl;
cout << "** ---------- **" << endl;
cout << "** Grand Total $" << setw(9) << grandTotal << " **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "********************************************" << endl << endl << endl;
cout << "Do you want to run this program again? (Y/N):";
cin >> answer;
answer = toupper(answer);
cout << endl << endl;
} while (answer == 'Y');
return 0;
}
プログラムの先頭に変数を初期化します。プログラムは一度実行しますが、ループを複数回実行します。したがって、各反復の開始時に変数を初期化する場合は、変数を0.0に初期化する必要があります。あなたがしたように宣言に初期設定を残すことは良い習慣ですが。 – Bartez