问题描述
当我运行程序时,每当我输入三个整数时,只有最后一个 else(所有首字母都不同)语句对其条件正确运行。但是,对于其他条件,只有最后一个 else if(第一个和最后一个首字母相同)运行。添加花括号后我也检查了它,但没有任何改变。
#include<stdio.h>
#include<stdlib.h>
int main()
{
char ch1,ch2,ch3;
printf("Enter 3 character values into ch1,and ch3: ");
scanf("%c%c%c",&ch1,&ch2,&ch3);
if(ch1==ch2)
{
if(ch2==ch3)
printf("All initials are the same!\n");
else
printf("First two initials are the same!\n");
}
else if(ch2==ch3)
{
printf("Last two initials are the same!\n");
}
else if(ch1==ch3)
{
printf("First and last initials are the same!\n");
}
else
{
printf("All initials are different!\n");
}
system("pause");
return 0;
}
解决方法
您发布的代码运行良好,只要您不在输入首字母之间输入任何空格字符!(我用 AAA
、{{1} }、AAB
、ABA
和 ABB
,并且都给出了正确的响应。)
但是,如果您要在首字母之间输入空格(即输入 ABC
),那么空格字符将被读取为输入(这就是 A A B
格式说明符的工作方式),因此,在这种情况下,三个首字母实际上是%c
、A
和
——给出一个看似不正确的答案。
要跳过输入之间的(可选)空白字符,只需在每个 A
格式说明符之间添加一个空格,如下所示:
%c