有了上一题的基础,再来看个复杂点的输入输出,1089题,A+B V 大家可以先阅读题目(链接见下方作业),题目一开始就告诉有多少组N,每一组又告诉有多少个数字M。大家可以结合样例理解:
输入:
1 2 3 | 2 4 1 2 3 4 5 1 2 3 4 5 |
输出:
1 2 | 10 15 |
这个题我们可以用前面格式的组合,即两层循环N,M分别控制次数,M个数字累加即可,依旧注意求和的变量要每次归零。
参考C语言代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include<stdio.h> int main() { int N,M; int a,sum; scanf ( "%d" ,&N); while (N--) { scanf ( "%d" ,&M); sum=0; while (M--) { scanf ( "%d" ,&a); sum=sum+a; } printf ( "%d\n" ,sum); } } |
参考C++代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int N,M; int a,sum; cin>>N; while (N--) { cin>>M; sum=0; while (M--) { cin>>a; sum=sum+a; } cout<<sum<<endl; } } |
参考Java代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int N=sc.nextInt(); while (N--!= 0 ) { int M=sc.nextInt(); int sum= 0 ; while (M--!= 0 ) { sum=sum+sc.nextInt(); } System.out.println(sum); } } } |
参考Python代码:
1 2 3 4 5 6 7 8 9 10 | n = int (input()) for i in range(n): sum=0 list=input().split() if list[0]== '0' : break for i in range(1,len(list)): list[i]= int (list[i]) sum+=list[i] print(sum) |
请大家理解并完成作业
1089 | A+B for Input-Output Practice (V) |
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程