0

我不确定我的一个公式是否错误,我是否在错误的区域放置了一些东西,或者我完全错过了一些东西。但是当我运行编。它会将前一张顾客餐桌的餐费加起来,而不是为每张新餐桌重新设置。有什么帮助吗?

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;

   }
4

3 回答 3

1

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

于 2012-11-27T01:49:56.947 回答
1

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

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

你应该subtotal+=price;改为subtotal=price;

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

于 2012-11-27T02:05:39.200 回答
-1

尝试使用它而不是 for 循环

整数计数器 = 1;// 不要忘记声明变量

而(计数器<=人){

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

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

}

于 2012-11-27T02:08:42.740 回答