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

无输入参数时毕达哥拉斯三元组程序无输出问题求助

问题排查与修复

核心问题

当不输入任何参数时,argc == 1,此时argv[1]是NULL指针,但你的代码直接调用了strtol(argv[1], &end, 10),这会触发未定义行为——可能导致程序崩溃、变量ende被赋予随机值,最终循环无法正确输出三元组。

修复后的代码

调整逻辑,仅当存在参数时才解析argv[1],否则直接使用默认值100:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    if (argc >= 3) {
        fprintf(stderr, "Superfluous argument was given! Only zero or one are allowed.\n");
        return 1;
    }

    long ende = 100; // 先设置默认值
    char *end;

    if (argc == 2) { // 仅当传入参数时才解析
        ende = strtol(argv[1], &end, 10);
        if (*end != '\0'){
            fprintf(stderr, "Given argument '%s' is no valid natural number!\n", argv[1]);
            return 1;
        }
        // 补充校验:确保输入是正整数,避免无意义的循环
        if (ende <= 0) {
            fprintf(stderr, "Given argument must be a positive natural number!\n");
            return 1;
        }
    }

    int a,b,c;
    for(a=1; a <= ende; a++){
        for(b=a; b <= ende; b++){
            for(c=b; c <= ende; c++){
                if(c*c == a*a + b*b){ // 循环已限制c<=ende,无需重复判断
                    printf("%d %d %d\n", a, b, c);
                }
            }
        }
    }

    return 0;
}

额外优化说明

  • 移除了if条件中重复的c<=ende判断,循环本身已经限制了c的范围,无需冗余校验。
  • 增加了输入参数的正整数校验,避免用户输入0或负数导致无意义的空循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:34:53