我的值不断增加,而不是在循环语句中重置

My values keep adding up, instead of resetting in my loop statement

本文关键字:语句 循环 不断增加 我的      更新时间:2023-10-16

我不确定是我的一个公式错了,还是我把一些东西放错了区域,或者我完全遗漏了一些东西。但当我运行程序时。它将把前一桌顾客的餐价相加,而不是为每一张新桌子重新设置。有什么帮助吗?

int main ()
{    
//These are the variables used for the formulas and inputs.
int people, counter;
float price, subtotal, tip, tax, total;
cout<<"How many people are at the table?" <<endl;
cin>>people;
//Use a while statement to start a loop
while (people!=0)
{
//Use a for statement inside the while to make a nested loop. It will ask the price of each meal.
for(counter=1; counter<=people; counter++)
{
cout<<"How much is the meal?: " <<endl;
cin>>price;
subtotal+=price;
tax=subtotal*.06;
if (people<5)
{
tip=subtotal*.18;
}
else
tip=subtotal*.20;
total=tax+subtotal+tip;
}
//This is the final output for the program. Which will be the bill.
cout<<setprecision(2) <<fixed;
cout<<left;
cout<<setw(20)<<"Subtotal: " <<"$" <<subtotal <<endl;
cout<<setw(20)<<"Sales Tax: " <<"$" <<tax <<endl;
cout<<setw(20)<<"Tip: " <<"$" <<tip <<endl;
cout<<setw(20)<<"Total: " <<"$" <<total <<endl;
cout<<" " <<endl;
cout<<setw(20)<<"How many people are at the table?" <<endl;
cin>>people;
}

您希望在while循环内和for循环之前将所有变量重置为0,尤其是subtotal

看起来像是初学者的代码(-:

不初始化变量是非常糟糕的编程,尤其是在C++中。你必须这样做(在变量创建上)!!仅供参考:未初始化=包含垃圾(未定义值)。

您应该将subtotal+=price;更改为subtotal=price;

total=tax+subtotal+tip;total+=tax+subtotal+tip;

尝试使用此选项而不是循环

int counter=1;//不要忘记声明变量

而(counter<=人){

//在这里使用你的价格公式

cout<< your desired outputs <<endl;
counter++;             // Update counter so the condition can be met eventually

}