A+B for Input-Output Practice (I-VIII)(二)
V.

圖片.png
題目的要求是我們首先輸入一個整型資料N,然後是N行,每一行的第一個數字M代表本行有M個需要相加的數,考慮到我們並不能確定N的個數,即有多少行的資料需要相加,於是我們引入陣列;作為一個系列的開端,深入理解它對後面的幾道很有幫助,接下來逐行對原始碼分析:
#include<stdio.h> int main() { int n,i,j,m=0,su=0,sum[100],a;//定義變數與陣列,注意到一些是初始化的,下面會有用; scanf("%d",&n);//接收鍵入的值作為題目中的N,存放在n中; while (m<n)//當m小於n時迴圈下去,對m初始化的意義所在; { scanf("%d",&i);//即每一行的第一個資料,存放在i中; for(j=1;j<=i;j++)//for迴圈,控制讀入i個數據; { scanf("%d",&a); su = su + a;//當執行完for迴圈,su便是這i個數據的和; } sum[m] = su;//執行完for迴圈,su的值便被存入陣列; m++; su = 0;//細節哦,執行一次後要對本次的su“初始化”,否則會影響下一組的結果; } m = 0; for(j=1;j<=n;j++,m++)//迴圈輸出一個數組的每個資料; { printf("%d\n",sum[m]);//留心換行,格式很重要; } return 0; }
VI.

圖片.png
感覺......這一道應該放在前面才對吧,跟第五道的不同在於不需要提前設定計算的組數,也就是說我們不需要再引入陣列了;直接輸入一行一行的資料,第一個資料代表本行需要相加的資料個數,敲下enter後返回本行的值並繼續輸入繼續計算,繼續輸入,繼續計算......
#include<stdio.h> int main() { int n,i,j,m=0,sum=0,a; while (scanf("%d",&i)!=EOF)//還是"!=EOF"應對連續輸入,連續計算的問題; { for(j=1;j<=i;j++) { scanf("%d",&a); sum = sum + a; } printf("%d\n",sum); m++; sum = 0;//細節細節...... } return 0; }
VII.
Problem Description
Your task is to Calculate a + b.
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.
Example Input
1 5
10 20
Example Output
6
30
看起來更簡單了是嗎?其實一開始我也這麼想,沒錯哇,就是這樣,要相信自己;
#include<stdio.h> int main() { int a=0,b=0; while(scanf("%d%d",&a,&b)!=EOF) { printf("%d\n",a+b); printf("\n"); } return 0; }
VIII.
Problem Description
Your task is to calculate the sum of some integers.
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.
Example Input
3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3
Example Output
10
15
6
第八題了,也是困住我時間最長的一道,提交了有七八次,換了幾個方案,剛開始是Wrong Answer,後來就一直是Presentation Error,很頭大,實在是無語。說到底,是細節,注意輸出的格式很重要;
#include<stdio.h> int main() { int n,sum,m,i,a[100];//定義變數與陣列; scanf("%d",&n); while(n--)//while迴圈,同時n做自減運算,技巧哦,當n自減到等於0的時候,因為C語言裡,“0”代表“假”,於是退出迴圈; { sum=0; scanf("%d",&m); for(i=1;i<=m;i++) { scanf("%d",&a[i]); sum=sum+a[i]; } if(n!=0) printf("%d\n\n",sum);//n不等於0的時候輸出兩個換行, if(n==0) printf("%d\n",sum);//n等於0,也意味著程式執行將要完畢了,只輸出一個換行; } }
後兩個的時候載入不出來圖片了,就把題目敲出來了;做完第八題才明白第七題的用意,第七題注意一下換行就好了,所以確實感覺很簡單的樣子,做到完第八題,才恍然大悟“原來是在給第八題打前站啊。。。”