我试图跟踪购买的杂货总量。
在我的程序中,每次我购买苹果,奶酪或面包时,程序都应该继续显示菜单。
但它一直在问“有多少苹果?”程序已经计算出苹果的总数而不是返回菜单选择另一个项目。
也许它与我使用过的循环类型有关。
我一直试图解决这个问题。任何帮助,将不胜感激。
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
double BUDGET;
const double apple= .60;
const double lb_cheese= 1.60;
const double loaf_bread = 2.50;
double total;
int count;
char choice;
double amount_left;
cout <<"Welcome! What is the budget for your picnic lunch?"<< endl;
cin>> BUDGET;
cout<<"Choose one of the following"<<endl;
cout<<"-------------------------------------"<<endl;
cout<<" MENU \n "<<endl;
cout<<"A-Apple B-Cheese C-Bread"<<endl;
cout<<" $0.60 $1.50 $2.50 "<<endl;
cout<<"-------------------------------------"<<endl;
cin>> choice;
while ((choice != 'Q') && (total <BUDGET)) //Q is the sentinel value to "quit" the program
{
switch(choice)
{
case 'A':
case 'a':
cout<<"How many apples?";
cin>> count;
total+= (count *apple);
break;
case 'B':
case 'b':
cout<<"How many pounds of cheese ?";
cin>> count;
total+= (count* lb_cheese);
break;
case 'C':
case 'c':
cout<<"How many loafs of bread?";
cin>> count;
total+= (count * loaf_bread);
break;
default:
cout<<"The entry you have entered is not valid, please try again."<<endl;
}
if( total > BUDGET)
{ cout<<"You have exceeded your budget please check your cart.\n\n";
break;
}
cout<<"Your total is: $"<<setprecision((2))<<fixed<<total<<endl;
amount_left= BUDGET-total;
cout<<"You have $"<<setprecision(2)<<fixed<<amount_left<<" left to spend."<<endl;
}
return 0;
}
答案 0 :(得分:1)
显示菜单不在循环中:
display menu
read option
while (option != quit) {
do some calculations
}
因此菜单只显示一次。您可以将其更改为无限循环:
while (true) {
display menu
read option
if (choice == 'Q' || total >= BUDGET)
break;
do some calculations
}
同时尽量避免编写超过50行的函数,将一些逻辑放入一些不同的函数中,只需调用此函数,将其分解为更小的部分,它将更容易阅读,也更容易理解。 / p>
答案 1 :(得分:1)
是的,在循环中显示菜单以显示您想要的次数,并且请记住将变量初始化为良好做法。
Double total = 0.00 //初始化。