2015-05-09 105 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; 

}