c程序未正确输入,输出错误
样本:c程序未正确输入,输出错误,c,string,C,String,样本: t n x some_string_having_A_and_B 预期产量 1 3 10 ABA 实际产量 -10 如果B的数量为奇数,则该代码给出-10,如果B的数量为偶数,则给出10。我知道编写程序的正确和最佳方法,但我不明白为什么这段代码会产生错误的输出 第一个scanf(“%c”)读取输入流中的上一个ENTER 快速修复建议:在规范中使用空格,使scanf忽略空白(输入为空白) 试一试 更好的修复建议:使用fgets()读取所有用户输入 if(st[j]='B') x=x
t
n x
some_string_having_A_and_B
预期产量
1
3 10
ABA
实际产量
-10
如果B
的数量为奇数,则该代码给出-10
,如果B
的数量为偶数,则给出10
。我知道编写程序的正确和最佳方法,但我不明白为什么这段代码会产生错误的输出 第一个scanf(“%c”)
读取输入流中的上一个ENTER
快速修复建议:在规范中使用空格,使scanf
忽略空白(输入为空白)
试一试
更好的修复建议:使用
fgets()
读取所有用户输入
if(st[j]='B')
x=x*-1;//你需要把括号放在这里
//正确的形式是x=x*(-1)
}
//更正的代码从这里开始
#包括
#包括
#包括
#包括
int main(){
int t,n,x,i,j;
char-st[50];
scanf(“%d”、&t);
对于(i=0;i在循环中打印st[j]
的值。
-10
10
if (scanf(" %c", &st[j]) != 1) /* error */;
// ^ ignore whitespace
char line[100];
...
fgets(line, sizeof line, stdin);
if (sscanf(line, "%c", &st[j]) != 1) /* error */;
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;