【发布时间】:2016-06-22 05:38:59
【问题描述】:
这段代码需要做 4 件事:
- 输入销售商品数量
- 输入每个销售项目的价格
- 输入税率
- 再次运行的选项
我已经完成了所有这些要求,但是当代码重复时,我唯一的问题出现了。我将总项目值保存在“while”后测试循环中的累加器中。当程序循环时,它不会清除累加器,而是继续在我的旧总值之上添加任何新值。
(例如,如果我第一次运行代码总共有 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。尽管像您一样在声明中保留初始化也是一个好习惯。
标签: c++ for-loop while-loop do-while