C++ 我的值不断增加,而不是在我的循环语句中重置
我不确定我的公式是错的,我把一些东西放在了错误的区域,还是完全遗漏了一些东西。但是当我运行程序时。它将把前一桌顾客的餐费加起来,而不是为每一张新桌子重新设置。有什么帮助吗C++ 我的值不断增加,而不是在我的循环语句中重置,c++,C++,我不确定我的公式是错的,我把一些东西放在了错误的区域,还是完全遗漏了一些东西。但是当我运行程序时。它将把前一桌顾客的餐费加起来,而不是为每一张新桌子重新设置。有什么帮助吗 int main () { //These are the variables used for the formulas and inputs. int people, counter; float price, subtotal, tip, tax, total; cout<<"How
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;
}
int main()
{
//这些是用于公式和输入的变量。
国际人员,柜台;
浮动价格、小计、小费、税金、总额;
您是否希望在循环中以及for
的之前将所有变量重置为0,尤其是小计看起来像是初学者的代码(-:
不初始化变量是非常糟糕的编程,特别是在C++中。
您必须这样做(在创建变量时)!!
仅供参考:未初始化=包含垃圾(未定义值)
您应该将subtotal+=price;
更改为subtotal=price;
和total=tax+subtotal+tip;
到total+=tax+subtotal+tip;
尝试使用此选项而不是for循环
int counter=1;//不要忘记声明变量
while(counter)只是好奇,还有其他方法吗?您也可以只在while循环中定义变量。请确保使用默认值进行初始化
cout<< your desired outputs <<endl;
counter++; // Update counter so the condition can be met eventually