c语言意外跳过判断语句

我并没有设置跳过判断,但是却自动跳过了,在while循环中
#include<stdio.h>
#include<stdlib.h>
int main()
{
void swap(float *,float *);
float firstnum,secnum;
char sortOrder;
printf("Enter two numbers:");
scanf("%f %f",&firstnum,&secnum);
printf("\nBefore the call to swap():\n");
printf(" The value in firstnum is %5.2f\n",firstnum);
printf(" The value in secnum is %5.2f\n",secnum);
if(firstnum>secnum)
swap(&firstnum,&secnum);
while(1)
{
printf("\nPlease input the sortorder(e(exit),a(ascending),d(descending)):");
scanf("%c",&sortOrder);

if(sortOrder=='d')
{
printf("\nAfter the call to swap():\n");
printf(" The value in firstnum is%5.2f\n",firstnum);
printf(" The value in secnum is%5.2f\n",secnum);
}
else if(sortOrder=='a')
{
printf("\nAfter the call to swap():\n");
printf(" The value in secnum is%5.2f\n",secnum);
printf(" The value in firstnum is%5.2f\n",firstnum);
}
else if(sortOrder=='e')
return 0;
else
printf("Error!");
}
system("pause");
return 0;
}
void swap(float *num1Addr,float *num2Addr)
{
float temp;
temp=*num1Addr;
*num1Addr=*num2Addr;
*num2Addr=temp;
}

完整代码如下,编译通过,附上结果,若有疑问,请追问。若满意,望采纳.

#include<stdio.h>
#include<stdlib.h>
int main()
{
void swap(float *,float *);
float firstnum,secnum;
char sortOrder;
printf("Enter two numbers:");
scanf("%f %f",&firstnum,&secnum);
printf("\nBefore the call to swap():\n");
printf("  The value in firstnum is %5.2f\n",firstnum);
printf("  The value in secnum is %5.2f\n",secnum);
if(firstnum>secnum)
swap(&firstnum,&secnum);

getchar();

while(1)
{
printf("\nPlease input the sortorder(e(exit),a(ascending),d(descending)):");
scanf("%c",&sortOrder);

getchar();

if(sortOrder=='d')
{
printf("\nAfter the call to swap():\n");
printf("  The value in firstnum is %5.2f\n",firstnum);
printf("  The value in secnum is %5.2f\n",secnum);
}
else if(sortOrder=='a')
{
printf("\nAfter the call to swap():\n");
printf("  The value in secnum is %5.2f\n",secnum);
printf("  The value in firstnum is %5.2f\n",firstnum);
}
else if(sortOrder=='e')
return 0;
else
printf("Error!");
}
system("pause");
return 0;
}
void swap(float *num1Addr,float *num2Addr)
{
float temp;
temp=*num1Addr;
*num1Addr=*num2Addr;
*num2Addr=temp;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-29

这是scanf("%c" 这个格式化输入语句的问题。

你在scanf语句输入char字符的时候,会有一个回车是默认接受的,因此你每次输入一个字符,会产生一个字符+一个回车符。

处理中,多种办法可以处理这个回车,比如:

else if (sortOrder=='\n')
 ;//do nothing
else
...

或者,也可以这样试试:

scanf("%c%c",&sortOrder);

本回答被网友采纳
第2个回答  2013-09-29
只要在两次scanf之后加上 getchar();就好了...望采纳
第3个回答  2013-09-29
else if(sortOrder=='e')
return 0;
这句话跳出了循环和整个程序
相似回答