C语言scanf输入异常致输出错误求助:代码排查与修复
C语言求和代码输出异常的原因及修复方法
问题原因
你的代码核心问题出在scanf的格式字符串设置上:
- 你写的格式是
"%d ,%d",这要求输入的两个整数之间必须严格匹配逗号加空格的格式,但你实际输入是换行输入每个数字(比如先输3回车,再输4),这导致scanf无法正确解析第二个整数。 - 未被正确赋值的变量(
_a、_b)会保留内存中的随机垃圾值,后续用这些值计算_c和d时,自然会出现异常的输出结果。
修复方案
有两种可行的修复方式,推荐第二种(更符合用户输入习惯):
方式1:按要求格式输入
每次输入一对数字时,严格按照数字 ,数字的格式输入,例如:
Enter 1 pair of numbers 3 ,4 Enter another pair of numbers 5 ,6
方式2:修改scanf格式字符串(推荐)
C语言中,%d格式符会自动忽略空格、换行、制表符等空白字符,所以把scanf的格式字符串改成"%d %d"(或直接"%d%d"),这样用户可以自由用空格、换行分隔数字,输入体验更友好。
修改后的完整代码:
#include <stdio.h> int main() { int a, _a, b, _b, c, _c, d; printf("Enter 1 pair of numbers\n"); scanf("%d %d", &a, &_a); printf("Enter another pair of numbers\n"); scanf("%d %d", &b, &_b); c = a + b; _c = _a + _b; d = c + _c; printf("The sum of first numbers in each pair is %d\n", c); printf("The sum of second numbers in each pair is %d\n", _c); printf("the sum of all the numbers is %d\n", d); return 0; }
测试输入示例:
Enter 1 pair of numbers 3 4 Enter another pair of numbers 5 6
对应输出:
The sum of first numbers in each pair is 8 The sum of second numbers in each pair is 10 the sum of all the numbers is 18
内容的提问来源于stack exchange,提问作者xherry24
相关产品推荐
相关产品推荐

