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

题目描述

Your task is to calculate the sum of some integers

输入格式

Input contains an integer N in the first line, and then N lines follow. Each line starts with a integer M, and then M integers follow in the same line

输出格式

For each group of input integers you should output their sum in one line, and you must note that there is a blank line between outputs.

样例输入

复制

3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3

样例输出

复制

10

15

6

代码解析

  1. 首先,代码通过#include <stdio.h>指令引入了标准输入输出库,这样程序就可以使用printfscanf等输入输出函数。

  2. 程序定义了main函数,这是C语言程序的入口点。main函数的返回类型是int,表示这个函数最终会返回一个整数值。

  3. main函数内部,首先定义了四个整型变量:mnsumj。其中:

    • n用于存储用户输入的组数。
    • m用于存储每组中的整数个数。
    • sum用于存储每组整数的总和。
    • j用于临时存储每次从输入中读取的整数。
  4. 使用scanf("%d", &n);函数从标准输入读取一个整数并将其存储在变量n中,这个整数表示用户将要输入的组数。

  5. 接下来是一个for循环,它将执行n次。每次循环都对应一组整数的输入和处理。

  6. 在每次for循环的开始,将sum变量初始化为0,准备计算新的一组整数的总和。

  7. 使用scanf("%d", &m);函数从标准输入读取一个整数并将其存储在变量m中,这个整数表示当前组中将要输入的整数个数。

  8. 然后是一个while循环,条件是m大于0。这个循环将一直执行,直到读取完当前组的所有整数。

  9. while循环内部,首先使用scanf("%d", &j);函数从标准输入读取一个整数并将其存储在变量j中。

  10. 然后,将读取到的整数j加到sum上,更新总和。

  11. 接着,将m减1,表示当前组中已读取的整数个数减1。

  12. while循环结束后,表示当前组的所有整数都已读取并加到了sum上。

  13. 使用printf("%d\n\n", sum);函数输出当前组的总和,后面跟两个换行符,用于分隔不同组的输出结果。

  14. for循环结束后,表示所有组的整数都已处理完毕。

  15. 最后,main函数返回0,表示程序正常结束。

源代码

#include <stdio.h>
int main(void)
{
	int m, n;
	int sum;
	int j;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		sum = 0;
		scanf("%d", &m);
		while (m)
		{
			scanf("%d", &j);
			sum = sum + j;
			m--;
		}
		printf("%d\n\n", sum);
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值