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

C语言如何实现scanf仅接收1次输入同时为两个变量赋值

C语言代码修正方案

你要实现的需求有两种简单的实现方式:

方式1:单次读取后手动赋值(最稳妥,可读性最高)

你不需要让scanf同时给两个变量赋值,只要读取输入到其中一个变量后,直接给另一个变量赋值即可,修改逻辑如下:

  1. 把第9行的错误scanf改成只给max赋值:scanf("%d", &max);
  2. 紧接着加一行input = max;,就能把输入值同时同步给input变量
    这种方式逻辑清晰,其他同学读你代码的时候也能一眼看懂两个变量的关联关系,符合你要的代码整洁规范的要求。

方式2:直接复用max变量输出

其实你完全不需要额外定义input变量,第14行的printf直接用max即可:printf("The sum of %d is %d.\n", max, sum);,这样可以减少不必要的变量定义,代码更简洁。


原有代码的其他隐藏问题

  • 第9行的scanf("%d", &max, &input);属于参数不匹配,格式符只有1个%d,后面多传的&input不会被处理,input会一直保持初始化的0值,这也是你现在输出不对的核心原因
  • 第17行的scanf("%d");缺少接收输入的变量参数,会触发未定义行为,建议改成getchar(); getchar();,第一个getchar吃掉之前输入残留的回车,第二个等待用户输入任意内容后退出,比原来的写法更稳妥。

修正后的完整代码

#include <stdio.h>
int main() {
    int count, sum, max, input;
    count = 1;
    sum = 0;
    input = 0;
    printf("This program will find the sum of your given input of an integer.\n");
    printf("Please enter the number you would like the sum of: ");
    // 单次读取输入到max
    scanf("%d", &max);
    // 同步赋值给input
    input = max;
    while (count <= max){
        sum = sum + count;
        count++;
    }
    printf("The sum of %d is %d.\n", input, sum);
    printf("==To exit the program, please enter anything, then press enter==");
    // 处理残留回车+等待用户输入
    getchar();
    getchar();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:57:04