请教一个《C Primer Plus》上一个代码的问题

2021-01-10 09:44:19 +08:00
 commoccoom
/*对用户输入的整数求和*/
#include <stdio.h>

int main(void)
{
	long num;
	long sum = 0L; 
	int status;

	printf("Please enter an integer to be summed ");
	printf("(q to quit): ");
	status = scanf_s("%1d", &num);  	

	while (status == 1) 
	{		
		sum = sum + num;
		printf("Please enter next integer (q to quit): ");
		status = scanf_s("%1d", &num);
	}

	printf("Those integers sum to %1d.\n", sum);
	return 0;
}

为什么我的运行结果是不对的啊😂 变成了 1+2+2+3=8

while 语句里面还循环了两次

991 次点击
所在节点    问与答
5 条回复
QBugHunter
2021-01-10 09:54:59 +08:00
while (status == 1)
?????
Chowe
2021-01-10 10:18:09 +08:00
%1d 表示长度为 1 的整形数
所以 12 会变成
1
2
更多有关细节,请查阅格式化输入输出
commoccoom
2021-01-10 10:44:02 +08:00
@Chowe 明白了,多谢!
msg7086
2021-01-10 15:45:34 +08:00
你是不是把 ld 打成了 1d ?
commoccoom
2021-01-10 16:01:34 +08:00
@msg7086 好像是的啊😅

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/743475

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX