Advertisement

杭电oj第1000题—— A + B Problem

阅读量:

题述如下:

复制代码
 Problem Description

    
 Calculate A + B.
    
  
    
 Input
    
 Each line will contain two integers A and B. Process to end of file.
    
  
    
 Output
    
 For each case, output A + B in one line.    \ 注意,此处强调一行一输出,即输出后跟“\n”
    
  
    
 Sample Input
    
 1 1    \ 注意,两数字间存在的字符为空格
    
  
    
 Sample Output
    
 2

参考程序如下:

复制代码
 #include <stdio.h>

    
  
    
 int main()
    
 {
    
     int a,b;
    
     while(scanf("%d %d",&a,&b)!=EOF)
    
     {
    
     printf("%d\n",a+b);
    
     }
    
 }

第一次自己编写的程序如下:

复制代码
 #include <stdio.h>

    
 int main(int argc,char **argv)
    
 {
    
     int a,b,c,d;
    
     do
    
     {
    
     printf("a=");
    
     c=scanf("%d",&a);
    
     getchar();
    
     printf("b=");
    
     d=scanf("%d",&b);
    
     getchar();
    
     if(c!=EOF&&d!=EOF)
    
         printf("a+b=%d\n",a+b);
    
     }
    
     while(c!=EOF&&d!=EOF);
    
     return 0;
    
 }

getchar()语句用于接收缓冲区的回车或空格符,由于此程序中存在两个scanf()语句,若不处理回车符将导致程序陷入死循环,无法正常接收输入。

代码本身没有错误,只是思路另类了些,但submit后显示wrong answer,多次排查后发现将程序中的解释性代码(如printf("a="))删去即可accepted,以下是accepted的代码:

复制代码
 #include <stdio.h>

    
 int main(int argc,char **argv)
    
 {
    
     int a,b,c,d;
    
     do
    
     {
    
     c=scanf("%d",&a);
    
     getchar();
    
     d=scanf("%d",&b);
    
     getchar();
    
     if(c!=EOF&&d!=EOF)
    
         printf("%d\n",a+b);
    
     }
    
     while(c!=EOF&&d!=EOF);
    
     return 0;
    
 }

总结:

  1. scanf()的用法:同时使用多个scanf()时,要注意处理存在于输入缓冲区中的转义字符;
  2. oj的局限:在oj中执行程序时,不用编写只有人才关心的解释性语句(注释无影响),若编写进去,oj系统反而会报错。

全部评论 (0)

还没有任何评论哟~