题目描述
Your task is to calculate the sum of some integers.
输入格式
Input contains multiple test cases, and one case one line. Each case starts with an integer N, and then N integers follow in the same line.
输出格式
For each test case you should output the sum of N integers 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
样例输出
10 15
代码解析
-
包含标准输入输出库:
#include <stdio.h>
这一行代码是预处理指令,它告诉编译器在实际编译之前包含标准输入输出库(stdio.h)。这个库提供了进行输入输出操作的功能,比如printf
和scanf
函数。 -
定义主函数:
int main(void)
是C程序的入口点,void
表示这个函数不接受任何参数。 -
定义变量:
int n
:用于存储用户输入的整数序列的长度。int sum
:用于累加每次序列中所有整数的和,初始化为0。int m
:用于存储当前读取的整数。
-
读取并处理序列:
- 使用一个
while
循环,条件是scanf("%d", &n)
的返回值不等于EOF。scanf
函数在这里用来从标准输入读取一个整数n
,代表将要输入的整数序列的长度。当用户输入EOF时,scanf
会返回EOF,此时循环结束。 - 在循环内部,首先将
sum
重置为0,为新的序列累计做准备。
- 使用一个
-
累加序列中的整数:
- 使用一个
for
循环,从0遍历到n-1
。在每次迭代中,使用scanf
函数读取下一个整数,并存储在变量m
中。 - 将每次读取的整数
m
累加到sum
变量中。
- 使用一个
-
输出序列的和:
printf("%d\n", sum);
这个函数调用用于输出当前序列的所有整数的总和。 -
函数返回:
return 0;
表示main
函数执行成功并返回0。在C语言中,main
函数的返回值通常用于表示程序的退出状态,其中0表示成功。
源代码
#include <stdio.h>
int main(void)
{
int n;
int sum;
int m;
while (scanf("%d", &n) != EOF)
{
sum = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &m);
sum += m;
}
printf("%d\n", sum);
}
return 0;
}