C语言题目: A+B for Input-Output Practice (VI)

题目描述

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

代码解析

  1. 包含标准输入输出库: #include <stdio.h> 这一行代码是预处理指令,它告诉编译器在实际编译之前包含标准输入输出库(stdio.h)。这个库提供了进行输入输出操作的功能,比如printfscanf函数。

  2. 定义主函数: int main(void) 是C程序的入口点,void表示这个函数不接受任何参数。

  3. 定义变量:

    • int n:用于存储用户输入的整数序列的长度。
    • int sum:用于累加每次序列中所有整数的和,初始化为0。
    • int m:用于存储当前读取的整数。
  4. 读取并处理序列:

    • 使用一个while循环,条件是scanf("%d", &n)的返回值不等于EOF。scanf函数在这里用来从标准输入读取一个整数n,代表将要输入的整数序列的长度。当用户输入EOF时,scanf会返回EOF,此时循环结束。
    • 在循环内部,首先将sum重置为0,为新的序列累计做准备。
  5. 累加序列中的整数:

    • 使用一个for循环,从0遍历到n-1。在每次迭代中,使用scanf函数读取下一个整数,并存储在变量m中。
    • 将每次读取的整数m累加到sum变量中。
  6. 输出序列的和: printf("%d\n", sum); 这个函数调用用于输出当前序列的所有整数的总和。

  7. 函数返回: 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;
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值