You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++新手求助:代码出现无限循环问题

解决你的C++无限循环问题

Hey there! No worries at all—everyone starts somewhere, and infinite loops are one of the most common pitfalls when you're just getting into coding. Let's figure out what's going wrong with your code.

问题根源

Looking at your code, the while (age != 0) loop will run forever once you enter an age that's not 0. Why? Because you never change the value of age inside the loop body. The loop condition checks if age is not 0, but since age stays the same as your initial input, the condition is always true, and the loop never exits.

两种修复方案

Depending on what you actually want the program to do, here are two ways to fix it:

方案1:允许用户多次输入(直到输入年龄为0退出)

If you want to let users keep entering age and mark values until they type 0 for age to quit, move the input prompts inside the loop so you get fresh values each time:

#include <iostream>
using namespace std;

int main() {
    int age, finalMark;
    
    while (true) {
        cout << "enter age: ";
        cin >> age;
        
        // Exit the loop immediately if age is 0
        if (age == 0) {
            break;
        }
        
        cout << "enter mark: ";
        cin >> finalMark;
        
        if (age < 30 && finalMark > 65) {
            cout << "You are an ideal candidate" << endl;
        } else {
            cout << "You are not the ideal candidate. Goodbye" << endl;
        }
    }
    
    return 0;
}

方案2:只判断一次输入

If you only need to check the user's input once (no repeated checks), you don't need a while loop at all—just use a simple if-else block:

#include <iostream>
using namespace std;

int main() {
    int age, finalMark;
    
    cout << "enter age: ";
    cin >> age;
    cout << "enter mark: ";
    cin >> finalMark;
    
    if (age < 30 && finalMark > 65) {
        cout << "You are an ideal candidate" << endl;
    } else {
        cout << "You are not the ideal candidate. Goodbye" << endl;
    }
    
    return 0;
}

小细节修正

I also fixed a tiny typo in your original message: "You are the an ideal candidate" had an extra "the"—the corrected version is in both code examples above.

内容的提问来源于stack exchange,提问作者Keán Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:03:27