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

C语言两整数求和程序异常:输入第一个数后程序终止

输入第一个整数后程序直接终止的问题分析与修复

你的代码核心错误是**scanf函数的参数传递错误**:

scanf读取输入到变量时,第二个参数必须传入变量的内存地址(指针),但你直接传了变量本身。执行scanf("%d", number_one)时,程序会把number_one的随机初始值当成内存地址去写入数据,这会触发非法内存访问,导致程序直接崩溃终止,因此输入第一个数后就无法继续。

修正后的代码

#include <stdio.h>

int main()
{
    int number_one;
    int number_two;

    printf("Please enter the first number: ");
    scanf("%d", &number_one); // 添加&取地址符

    printf("Please enter the second number: ");
    scanf("%d", &number_two); // 添加&取地址符

    printf("The sum of the two numbers is: %d", number_one + number_two);
    return 0; // 补充main函数标准返回值,符合C语言规范
}

关键说明

  • &是取地址运算符,它会返回变量的内存地址,scanf通过这个地址才能将用户输入的值写入对应的变量中。
  • 补充return 0;是为了符合C语言标准,明确表示程序正常执行结束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:07:34