我的值不断增加,而不是在循环语句中重置
My values keep adding up, instead of resetting in my loop statement
我不确定是我的一个公式错了,还是我把一些东西放错了区域,或者我完全遗漏了一些东西。但当我运行程序时。它将把前一桌顾客的餐价相加,而不是为每一张新桌子重新设置。有什么帮助吗?
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
}
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如果 else 语句不断循环
- do while 循环中的 if 语句以 yes 或 no 结尾
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 如果语句不会在 do - while 循环中运行
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 什么可以用来替换代码中的循环和 if 语句?
- C++ 访问 if 语句(如果它们在 for 循环中)
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如何仅在父循环的所有迭代都为真时才执行嵌套的 if 语句?
- 有没有办法制作一个 c++ 宏(或类似的东西),它使用户语句被 while 循环的预定义函数包围?
- 为什么这个 IF 语句在循环内不打印
- 当我的 if 语句在字符串中找到空格时,在无限循环中切换
- 我的 if 语句打印在我的 while 循环中的每个 if 语句上,无论它是否为假
- C++-循环中的If语句工作不正常
- C++切换语句循环回菜单
- 如果 else 语句循环或重复,直到 true
- C++:使用嵌套的 if/else 语句循环进行故障排除
- 有没有办法使c++ Switch语句循环回到第一种情况?
- 为什么这个'if'语句循环?