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

C语言程序问题:do-while循环无法正常工作

Fixing the Input Loop Issue

Hey there! Let's sort out this problem so your program keeps prompting for new numbers even after handling valid inputs.

The Root Cause

It sounds like your current code only runs the input-check logic once. When you enter a valid number (between 2 and 20), the program processes it and then exits because there's no loop to keep the process going. Invalid numbers work as expected because you probably have logic to re-prompt, but that logic doesn't wrap the valid case.

The Solution: Wrap Everything in a Loop

The fix is simple—put your entire input and validation logic inside an infinite loop. This way, after handling a valid number (or skipping an invalid one), the program automatically goes back to asking for new input.

Example in Python

Here's a straightforward implementation that follows your requirements:

while True:
    # Handle non-integer input gracefully (optional but helpful)
    try:
        num = int(input("Enter a number: "))
    except ValueError:
        print("Whoops, please enter a valid whole number!")
        continue

    # Check if the number falls in the valid range
    if 2 < num < 20:
        print(f"Processed result: {num}")  # Replace with your custom result display
    # For invalid numbers, we just skip printing and loop back automatically

Example in Java

If you're using a compiled language like Java, a do-while loop works perfectly here:

import java.util.Scanner;

public class ContinuousInputHandler {
    public static void main(String[] args) {
        Scanner inputScanner = new Scanner(System.in);
        
        do {
            System.out.print("Enter a number: ");
            int userNum = inputScanner.nextInt();
            
            if (userNum > 2 && userNum < 20) {
                System.out.println("Valid result: " + userNum); // Add your result logic here
            }
            // No extra code needed for invalid numbers—loop restarts on its own
        } while (true);
    }
}

Quick Tips

  • The while(true)/do-while(true) creates an infinite loop that runs until you manually stop the program (e.g., Ctrl+C).
  • For valid inputs, we display the result and the loop naturally cycles back to ask for more input.
  • Optional: If you want users to exit gracefully, add a check—like if they enter 0 or "quit", use break to exit the loop.

内容的提问来源于stack exchange,提问作者James Macathy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:39:19