gpt4 book ai didi

C++ "while"解释

转载 作者:行者123 更新时间:2023-11-27 23:29:38 26 4
gpt4 key购买 nike

我不是很确定 while(choice == 1 || choice ==2);谁能解释一下。我明白这一点

if(choice ==1)
displayMonthly(rainfall);
else if(choice == 2)
displayTotal(rainfall);

我只是不明白这之后的代码。谁能给我解释一下。

int main()
{
//declare variable and array
int choice = 0;
double rainfall[12] = {0.0};

//get rainfall amounts
for(int x =0;x<12;x++)
{
cout << "Enter rainfall for month "<< x+1<< ": ";
cin >> rainfall[x];
}

do
{
//display menu and get menu choice
cout <<endl;
cout << "1 Display monthly amounts" << endl;
cout << "2 Display total amount" << endl;
cout << "3 End program" << endl;
cout << "Enter your choice : ";
cin >> choice;

//call appropriate function or end program
if(choice ==1)
displayMonthly(rainfall);
else if(choice == 2)
displayTotal(rainfall);
}while (choice == 1 || choice ==2);

return 0;
}

最佳答案

它告诉你只要选择 1 或 2 就一直循环,但它与 if 语句完全分开。

也可以编码为

while(true) {
cout stuff...

if(choice==1)
...
else if(choice==2)
...
else
break;
}

这可能更具可读性,但一些老同学如果看到 while(true) 会立即大吃一惊——这曾经被当作一个大红旗提醒人们,表明潜在的错误(显然任何人都完全无法分析代码,因为功能没有什么不同)。

关于C++ "while"解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6393669/

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