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

C语言加法题程序优化:限制随机数范围并规避0+0场景

优化C语言加法测试程序:限制随机数范围并避免0+0组合

原代码存在几个关键问题导致你遇到的现象:

  • 缺失必要头文件,编译会失败
  • 不必要地使用变长数组,完全可以用普通变量替代
  • 随机数范围未按需调整,且未过滤0+0的组合

以下是修复并优化后的代码:

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

int Math()
{
    int result;
    srand(time(NULL)); // 初始化随机数种子

    for (int i = 0; i < 10; i++)
    {
        // 生成1-20之间的随机数,彻底避免0的出现
        int num1 = rand() % 20 + 1;
        int num2 = rand() % 20 + 1;

        printf("\nQuestion %d:", i + 1);
        printf("\n%d + %d = ", num1, num2);
        scanf("%d", &result);

        if (result == num1 + num2)
        {
            printf("\nCorrect answer!\n");
        }
        else
        {
            printf("\nWrong answer! The correct result is %d\n", num1 + num2);
        }
    }

    return 0;
}

// 补充程序入口,原代码缺少main函数
int main()
{
    Math();
    return 0;
}

如果你的需求是允许单个0,但禁止0+0的组合,可以把随机数生成部分替换为:

int num1, num2;
// 循环过滤0+0的组合
do {
    num1 = rand() % 50; // 生成0-49的随机数
    num2 = rand() % 50;
} while (num1 == 0 && num2 == 0);

关键修改说明:

  1. 补充必要头文件:添加stdio.h(输入输出)、stdlib.h(随机数函数)、time.h(时间种子),确保代码能正常编译。
  2. 替换冗余数组:用普通变量num1和num2存储随机数,去掉不必要的变长数组,简化逻辑。
  3. 限制随机数范围:通过rand() % 20 + 1生成1-20的整数,既缩小数值规模,又彻底避免0的出现;若需保留单个0,用do-while循环过滤0+0组合。
  4. 补充程序入口:添加main函数,让代码具备可执行性。
  5. 优化反馈提示:错误回答时显示正确结果,提升测试体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:02:52