此代码需要做4件事:
我已经完成了所有这些要求,但我的唯一问题是代码重复时出现的问题。我将总项目值保存在'内的累加器中。测试后循环。当程序循环时,它不会清除累加器,并继续只在我的旧总值之上添加任何新值。
(例如,如果我的第一次运行代码共有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 :(得分:2)
您需要在循环内重置titemValue的值,但它在循环外部设置。变化
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;
到
char answer = ' ';
int saleItems = 0;
double itemValue = 0.0;
double titemValue; // (changed)
double taxPerc = 0.0;
do {
titemValue = 0.0; // (new)
cout << "How many sales items do you have? : ";
cin >> saleItems;
您不一定需要更改第一行,但将其值设置为相同的两次没有任何意义。但是,如果您仍然进行双初始化,AFAIK的某些编译器可能会对其进行优化。有些则不会,例如默认的Debug配置设置中的Visual Studio。