天天看點

【入門推薦】ACM之輸入

輸入_第一類:

輸入不說明有多少個Input Block,以EOF為結束标志。

例1:

Description:

你的任務是計算a+b

Input

輸入包含多行資料,每行有兩個整數a和b,以空格分開。

Output

對于每對整數a,b,輸出他們的和,每個和占一行。

Sample Input

1 5

10 20

Sample Output

6

30

#include <stdio.h>

 int main()

 {

    int a,b;

        while(scanf("%d %d",&a, &b) != EOF)            printf("%d/n",a+b);

 }

本類輸入解決方案:

C文法:

       while(scanf("%d %d",&a, &b) != EOF)

       {

        ....

    }

C++文法:

       while( cin >> a >> b )

    {

        ....

    }

說明:

Scanf函數傳回值就是讀出的變量個數,如:scanf( “%d  %d”, &a, &b );

如果隻有一個整數輸入,傳回值是1,如果有兩個整數輸入,傳回值是2,如果一個都沒有,則傳回值是-1。

EOF是一個預定義的常量,等于-1。

輸入_第二類:

輸入一開始就會說有N個Input Block,下面接着是N個Input Block。

例2:

Description:

你的任務是計算a+b

Input

輸入包含多行資料,第一行有一個整數N,接下來N行每行有兩個整數a和b,以空格分開。

Output

對于每對整數a,b,輸出他們的和,每個和占一行。

Sample Input

2

1 5

10 20

Sample Output

6

30

#include <stdio.h>

 int main()

 {

    int n,i,a,b;

        scanf("%d",&n);

for(i=0;i<n;i++)

{

       scanf("%d %d",&a, &b);

      printf("%d/n",a+b);

 }

 }

本類輸入解決方案:

C文法:

       scanf("%d",&n) ;

       for( i=0 ; i<n ; i++ )

    {

        ....

    }

    C++文法:

       cin >> n;

    for( i=0 ; i<n ; i++ )

    {

        ....

    }

輸入_第三類:

輸入不說明有多少個Input Block,但以某個特殊輸入為結束标志。

例3:

Description:

你的任務是計算a+b

Input

輸入包含多行資料,每行有兩個整數a和b,以空格分開。測試資料以0 0結束。

Output

對于每對整數a,b,輸出他們的和,每個和占一行。

Sample Input

1 5

10 20

0 0

Sample Output

6

30

#include <stdio.h>

 int main()

 {

       int a,b;

       while(scanf("%d %d",&a, &b) &&!(a==0 && b==0))

      printf("%d/n",a+b);

 }

本類輸入解決方案:

C文法:

       while(scanf("%d",&n)  && n!=0 )

       {

        ....

    }

C++文法:

       while( cin >> n && n != 0 )

    {

        ....

    }

輸入_第四類:

以上幾種情況的組合

例4:

Description:

你的任務是計算多個數字的和

Input

輸入包含多行資料,每行以一個整數N開始,接着有N個整數,以空格分開。測試資料以0結束。

Output

輸出每行的N個整數之和,每個和占一行。

Sample Input

4 1 2 3 4

5 1 2 3 4 5

Sample Output

10

15

本文來自CSDN部落格,轉載請标明出處:http://blog.csdn.net/niyibo/archive/2009/09/11/4540928.aspx