6.18算法学习(A+B练习2)
practice5
Input
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.
Output
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.
Sample Input
2
4 1 2 3 4
5 1 2 3 4 5
Sample Output
10
15
分析:先输入一个数,那个数代表下面有几个回合;再输入一个数,代表这一个回合有几个数;当回合结束的时候程序运行结束。输出的数是每个回合输入数字的累加和。
第一次代码:
#include<stdio.h>
int main()
{
int N,M,a,sum;
while(scanf("%d",&M)!=EOF)
{
while(M--)
{
scanf("%d",&N);
sum=0;
while(N--)
{
scanf("%d",&a);
sum=sum+a;
}
} printf("%d\n",sum);
}
return 0;
}
报错!!!
但是在codeblocks上面的运行结果是正确的,后来我用vscode运行,发现了问题
(第十七行输出应该移动到上面,放在这个位置上只会输出最后一组的sum值)
修改后ac的代码如下:
#include<stdio.h>
int main()
{
int N,M,a,sum;
if(scanf("%d",&M)!=EOF)
{
while(M--)
{
scanf("%d",&N);
sum=0;
while(N--)
{
scanf("%d",&a);
sum=sum+a;
}printf("%d\n",sum);
}
}
return 0;
}
practice6
Your task is to calculate the sum of some integers.
Input
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.
Output
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.
Sample Input
4 1 2 3 4
5 1 2 3 4 5
Sample Output
10
15
分析:上一道题的简化版,不用输局数,直接来
代码:
#include<stdio.h>
int main()
{
int t,a,sum=0;
while(scanf("%d",&t)!=EOF)
{
sum=0;
while(t--)
{
scanf("%d",&a);
sum+=a;
}
printf("%d\n",sum);
}
return 0;
}
practice7
Input
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.
Output
For each pair of input integers a and b you should output the sum of a and b, and followed by a blank line.
Sample Input
1 5
10 20
Sample Output
6
30
分析:两个数累加,输出之前要间隔一个空格,相当于换行两次
代码:
#include<stdio.h>
int main()
{
int a,b;
while(scanf("%d",&a)!=EOF&&scanf("%d",&b)!=EOF)
printf("%d\n\n",a+b);
return 0;
}
practice8
Input
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.
Output
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.
Sample Input
3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3
Sample Output
10
15
6
分析:这道题的注意点是最后一行不用空格,所以通过if语句和break语句跳出当前循环
代码:
#include <stdio.h>
int main()
{
int a[100],i,j,n,N,sum;
scanf("%d",&n);
for(i=0;i<n;i++)
{
sum=0;
scanf("%d",&N);
for(j=0;j<N;j++)
{
scanf("%d",&a[j]);
sum=sum+a[j];
}
printf("%d\n",sum);
if(i==n-1)
break;
printf("\n");
}
return 0;
}