gpt4 book ai didi

c++ - 我在 C++ 初学者中遇到了无限循环问题

转载 作者:行者123 更新时间:2023-11-28 04:44:26 25 4
gpt4 key购买 nike

编程方面的新手想知道您是否可以提供帮助。我的代码出现无限循环

int main()
{
int age, finalMark;

cout << "enter age: ";
cin >> age;
cout << "enter mark: ";
cin >> finalMark;

while (age != 0)
{
if(age < 30 && finalMark > 65)
cout << "You are the an ideal candidate" << endl;

else
cout << "You are not the ideal candidate. Goodbye" << endl;
}

return 0;
}

任何帮助将不胜感激,抱歉,如果它非常基本/容易解决

最佳答案

当您使用循环时,请确保条件在某个时刻不为真,否则,您将陷入无限循环。

这里如果 age 的值最初不为 0,那么您将永远不会跳出循环,因为您不会在循环内的任何地方更改它。

while (age != 0)
{
if(age < 30 && finalMark > 65)
cout << "You are the an ideal candidate" << endl;

else
cout << "You are not the ideal candidate. Goodbye" << endl;
}

如果您想简单地检查一个条件,并且只根据其结果做某事一次,请使用“if”语句:

if (age != 0)
{
if(age < 30 && finalMark > 65)
cout << "You are the an ideal candidate" << endl;

else
cout << "You are not the ideal candidate. Goodbye" << endl;
}

关于c++ - 我在 C++ 初学者中遇到了无限循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49566669/

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