gpt4 book ai didi

c++ - 简单程序 - 菜单只显示一次

转载 作者:行者123 更新时间:2023-11-28 02:53:52 24 4
gpt4 key购买 nike

我正在尝试跟踪购买杂货的总量。

在我的程序中,每次我购买苹果、奶酪或面包时,程序都应该继续显示菜单。

但它一直在问“有多少个苹果?”在程序已经计算出苹果的总数之后,而不是返回菜单选择另一个项目。

可能与我使用的循环类型有关。

我一直在努力解决这个问题。任何帮助,将不胜感激。

#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;
}

最佳答案

显示菜单不在循环中:

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 行的函数,将一些逻辑放在一些不同的函数中并调用这个函数,将其分解成更小的部分,这样会更容易阅读,也更容易理解。

关于c++ - 简单程序 - 菜单只显示一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22444824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com