【发布时间】:2020-08-26 01:10:06
【问题描述】:
我是 C 语言的新手,在这里我有一个代码可以使用 do-while 循环添加用户输入的任意数字。
例如,如果他们输入 1,然后是 2,然后是 3,最后是 0,它应该打印出 6。所以,我的问题是如何在不以 0 结尾的情况下添加这 3 个数字。
我的意思是如何让我的代码知道我已经输入了所有的数字?
例如:
1
2
3
output: 6
or
10
10
10
10
output: 40
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
static char syscall_buf[256];
#define syscall_read_int() atoi(fgets(syscall_buf,256,stdin))
main()
{
int input;
int result = 0;
do {
input = syscall_read_int();
result = result + input;
} while(input != 0);
printf("%i\n", result);
}
【问题讨论】:
-
你想让他们输入什么而不是
0来表示结束? -
当普通函数可以工作时不要使用
#define。 -
不确定是否了解您。如果您真的不想添加 0,只需执行
while而不是do while:while ((input = syscall_read_int()) != 0) result ++ input;如果您不想管理 0 情况,如何检测 EOF?atoi不是一个好选择,输入一个非数字,你会循环到世界末日……或者关机 -
您正在输入
fgets,因此您可以在有空行时结束。您已将其隐藏在define中。把它放在代码中。
标签: c loops while-loop do-while