Online Judge計算整數的和

jiangzhengdong發表於2013-03-18
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.
 

Sample Input
3 4 1 2 3 4 5 1 2 3 4 5 3 1 2 3
 

Sample Output
10 15 6 我的程式碼如下: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main(int argc,char **argv){     int row; //將要輸入的行     int rowmax;//每行輸入整數個數     scanf("%d",&row);     int *pt[row];     int result[row];     memset(result,0,sizeof(int) * row);     int i=row;     for(;row>0;row--){         scanf("%d",&rowmax);         pt[row-1]=(int *)malloc(rowmax * sizeof(int));         if(pt[row-1]==NULL){             perror(strerror(errno));         }         else{             for(;rowmax>0;rowmax--){                 scanf("%d",pt[row-1]);                 result[row-1]+=*pt[row-1];                 pt[row-1]++;             }         }     }            for(;i>0;i--)         printf("%d\n\n",result[i-1]);     return 0; } 注:我動態申請的空間用完後沒有釋放,因不知指標陣列空間如何釋放。 下面程式碼是別人所寫,拿來對比:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
 
int main (int argc,char*argv[])
{   
    int row;
    int i,j=0;
    char num;
    int* result=NULL;
    printf("Enter the row: ");
    scanf("%d",&row);
    result = malloc(row*sizeof(int));
    memset(result,0,sizeof(result));
    getchar();
    for (i=0;i<row;i++)
    {
        result[i] = 0;
        num = getchar();
        while(1)
        {
            num = getchar();
            if (num == '\n')
            {
                break;
            }
            else if (num != ' ')
            {
                result[i]+=(num-0x30);
            }
        }
    }
    for (i=0;i<row;i++)
    {
        printf("%d\n\n",result[i]);
    }
    return 0;
}

相關文章