题目描述
Your task is to Calculate the sum of some integers.
输入格式
Input contains multiple test cases. Each test case contains a integer N, and then N integers follow in the same line. A test case starting with 0 terminates the input and this test case is not to be processed.
输出格式
For each group of input integers you should output their sum in one line, and with one line of output for each line in input.
样例输入
4 1 2 3 4 5 1 2 3 4 5 0
样例输出
10 15
代码解析
-
包含标准输入输出库:
#include <stdio.h>
这一行代码是预处理指令,它告诉编译器在实际编译之前包含标准输入输出库(stdio.h)。这个库提供了进行输入输出操作的功能,比如printf
和scanf
函数。 -
定义主函数:
int main(void)
是C程序的入口点,void
表示这个函数不接受任何参数。 -
定义变量:
int n
:用于存储用户输入的整数序列的数量。int m
:用于存储序列中的单个整数。int sum
:用于累加序列中所有整数的和,初始化为0。
-
创建循环读取序列:
while (scanf("%d", &n))
创建了一个循环,条件是scanf
成功读取一个整数到变量n
。只要n
不为0,循环就会继续执行。 -
处理输入序列:
- 每当读取到一个新的
n
(不为0),程序首先将sum
重置为0。 - 使用一个
for
循环,从0遍历到n-1
,每次迭代中使用scanf
函数读取下一个整数,并存储在变量m
中。 - 将每次读取的整数
m
累加到sum
变量中。
- 每当读取到一个新的
-
输出序列和:
printf("%d\n", sum);
这个函数调用用于输出当前序列的所有整数的和。 -
退出循环条件:
- 当用户输入0时,
scanf
函数返回0,这会导致while
循环的条件不成立,从而跳出循环。
- 当用户输入0时,
-
函数返回:
return 0;
表示main
函数执行成功并返回0。在C语言中,main
函数的返回值通常用于表示程序的退出状态,其中0表示成功。
源代码
#include <stdio.h>
int main(void)
{
int n;
int m;
int sum;
while (scanf("%d", &n))
{
if (n == 0)
break;
sum = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &m);
sum = sum + m;
}
printf("%d\n", sum);
}
return 0;
}