2015-05-09 70 views
0
#include <stdio.h> 
#include <string.h> 
#include <math.h> 
#include <stdlib.h> 

int main() { 

    int t,n,x,i,j; 
    char st[50]; 
    scanf("%d",&t); 
    for(i=0;i<t;i++) 
     { 
      scanf("%d %d",&n,&x); 
      for(j=0;j<n;j++) 
       { 
        scanf("%c",&st[j]); 
        if(st[j]=='A') 
         x=x*1; 
        if(st[j]=='B') 
         x=x*-1; 
       } 
      printf("%d",x); 
     } 

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    return 0; 
} 

輸入代碼的格式爲:C程序不採取輸入正確和producding錯誤輸出

t 
n x 
some_string_having_A_and_B 

樣品:

1 
3 10 
ABA 

預期輸出

-10 

實際產量

10 

此代碼給-10如果B數爲奇數和10如果B數爲偶數。我知道編寫程序的正確和最佳方式,但我無法弄清,爲什麼這個代碼產生錯誤的輸出。

+1

嘗試打印'在環路'ST [j]的值。 – Barmar

回答

0

第一個scanf("%c")讀取輸入流中的前一個ENTER。

對於快速修復的建議:使用規範內的空間讓scanf忽略空格(回車是空格)。

嘗試

if (scanf(" %c", &st[j]) != 1) /* error */; 
//  ^ignore whitespace 

建議更好的解決辦法:讀取所有用戶輸入與fgets()

char line[100]; 
... 
fgets(line, sizeof line, stdin); 
if (sscanf(line, "%c", &st[j]) != 1) /* error */; 
-1
if(st[j]=='B') 
        x=x*-1;// you need to put bracket here.on -1 
//correct form is x=x*(-1) 
       } 


    //corrected code starts from here 
    #include <stdio.h> 
#include <string.h> 
#include <math.h> 
#include <stdlib.h> 

int main() { 

     int t,n,x,i,j; 
     char st[50]; 
     scanf("%d",&t); 
     for(i=0;i<t;i++) 
      { 
      scanf("%d %d",&n,&x); 
      for(j=0;j<n;j++) 
       { 
       scanf("%c",&st[j]); 
       if(st[j]=='A') 
        x=x*1; 
       if(st[j]=='B') 
        x=x*(-1);// you need to put bracket here.on -1 
       } 
      printf("%d",x); 
      } 

/* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
return 0; 

}