題目描述
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
樣例輸出
復制
10156
代碼解析
-
首先,代碼通過
#include <stdio.h>
指令引入了標準輸入輸出庫,這樣程序就可以使用printf
和scanf
等輸入輸出函數。 -
程序定義了
main
函數,這是C語言程序的入口點。main
函數的返回類型是int
,表示這個函數最終會返回一個整數值。 -
在
main
函數內部,首先定義了四個整型變量:m
、n
、sum
和j
。其中:n
用于存儲用戶輸入的組數。m
用于存儲每組中的整數個數。sum
用于存儲每組整數的總和。j
用于臨時存儲每次從輸入中讀取的整數。
-
使用
scanf("%d", &n);
函數從標準輸入讀取一個整數并將其存儲在變量n
中,這個整數表示用戶將要輸入的組數。 -
接下來是一個
for
循環,它將執行n
次。每次循環都對應一組整數的輸入和處理。 -
在每次
for
循環的開始,將sum
變量初始化為0,準備計算新的一組整數的總和。 -
使用
scanf("%d", &m);
函數從標準輸入讀取一個整數并將其存儲在變量m
中,這個整數表示當前組中將要輸入的整數個數。 -
然后是一個
while
循環,條件是m
大于0。這個循環將一直執行,直到讀取完當前組的所有整數。 -
在
while
循環內部,首先使用scanf("%d", &j);
函數從標準輸入讀取一個整數并將其存儲在變量j
中。 -
然后,將讀取到的整數
j
加到sum
上,更新總和。 -
接著,將
m
減1,表示當前組中已讀取的整數個數減1。 -
當
while
循環結束后,表示當前組的所有整數都已讀取并加到了sum
上。 -
使用
printf("%d\n\n", sum);
函數輸出當前組的總和,后面跟兩個換行符,用于分隔不同組的輸出結果。 -
當
for
循環結束后,表示所有組的整數都已處理完畢。 -
最后,
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;
}