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

标签 c++

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

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/

相关文章:

c++ - 为类重载运算符 new

c++ - 为多线程环境包装 c++ new/delete 的安全/好方法

C++ 如何修复 typedef 模板和类之间的依赖关系问题

c++ - 方法返回类型的前向声明

c++ - C++ 可以在全局范围内拥有代码吗?

c++ - 使用 BOOST 时出现 LNK 错误 1561

c++ - 如何在 Linux 上以编程方式 (C/C++) 获取国家/地区代码?

c++ - 运算符顺序在这里

c++ - 是否有像包含目录别名这样的概念?

c++ - 构造函数 Parent 在构造函数 Child 的初始化列表中被调用