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

C语言求解欧拉计划第7题:控制台无输出,请求排查代码问题

问题分析与修复

你的代码运行无输出的核心原因是内层的while(check == true)循环导致了死循环,当测试的数是素数时,这个循环永远无法退出,程序直接卡死,自然不会有任何输出。

具体问题拆解

当number是素数时,进入for循环后,以number=5为例:

  • i=2,满足i < sqrt(5)(≈2.236)的条件,进入循环
  • 内层while(check == true)启动,此时check为true,但5%2 != 0,不会修改check的值,导致这个while循环无限执行,程序彻底卡住,后续的printf和循环逻辑都无法运行。

另外你的代码还有两个次要问题:

  • for循环的条件i < sqrt(number)不准确,应该改为i <= sqrt(number)或者i*i <= number,否则会漏掉刚好能被平方根整除的合数(比如4,sqrt(4)=2,i<2不会检查到2)
  • sqrt函数返回的是浮点数,直接和整数i比较可能有精度问题,建议用i*i <= number替代,避免浮点运算误差。

修复后的代码

把内层多余的while循环去掉,直接在for循环里判断即可:

#include <stdio.h>
#include <stdbool.h>

int main(int argc, char *argv[]) {
    int number = 2; // 待测试的数
    int counter = 0; // 已找到的素数计数
    bool check = true; // 标记是否为素数

    while(counter != 10001) {
        if(number == 2) {
            counter++;
            number++;
        } else {
            check = true; // 每次测试前重置标记
            for(int i = 2; i*i <= number; i++) {
                if(number % i == 0) {
                    check = false;
                    break; // 找到因数后直接退出循环,无需继续检查
                }
            }

            if(check == true) {
                counter++;
            }

            printf("%d, %d\n", number, counter); // 测试输出
            number += 2;
        }
    }

    printf("%d", number - 2);
    return 0;
}

额外说明

  • 去掉内层while循环后,一旦找到能整除number的因数,就标记check为false并跳出for循环,避免不必要的计算
  • 用i*i <= number替代sqrt(number),既避免浮点运算的精度问题,也提升了一点效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:15:01