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

题目描述

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

代码解析

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

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

  3. 定义变量:

    • int n:用于存储用户输入的整数序列的数量。
    • int m:用于存储序列中的单个整数。
    • int sum:用于累加序列中所有整数的和,初始化为0。
  4. 创建循环读取序列: while (scanf("%d", &n)) 创建了一个循环,条件是scanf成功读取一个整数到变量n。只要n不为0,循环就会继续执行。

  5. 处理输入序列:

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

  7. 退出循环条件:

    • 当用户输入0时,scanf函数返回0,这会导致while循环的条件不成立,从而跳出循环。
  8. 函数返回: 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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值