这个小程序错在哪里?

来源:百度知道 编辑:UC知道 时间:2024/07/02 01:06:02
#include "stdio.h"
main()
{
float x,y,n;
char ch;
printf("please enter 2 numbers");
scanf("%f%f",&x,&y);
printf("%f%f",x,y);
printf("enter the +-*/") ;
scanf("%c",&ch);
switch(ch)
{
case '+':n=x+y;break;
case '-':n=x-y;break;
case '*':n=x*y;break;
case '/':n=x/y;
}
printf("%5f",n);
}
这个怎么不能运算啊,ch无法赋值.第十行好象被跳过去了,结果总是:0

错误的根本原因在于scanf语句和c++的cin语句不同,它本身没有刷新流的功能,所以下面的scanf("%c",&ch)其实是把上面输入两个数后的换行符(即回车)赋给了ch。所以需要改为scanf("\n%c",&ch),也就是用\n刷新流后即可。

#include "stdio.h"
#include "conio.h"
main()
{
float x,y,n;
char ch;
renew:printf("please enter 2 numbers:");
scanf("%f,%f",&x,&y);
printf("%f%f",x,y);
printf("enter the +-*/:") ;
scanf("%c",&ch);
scanf("%c",&ch);
switch(ch)
{
case '+':n=x+y;break;
case '-':n=x-y;break;
case '*':n=x*y;break;
case '/':n=x/y; break;
default:printf("renew");
printf("\n");
goto renew;
}
printf("%5f",n);
getch();
}
你的scanf("%c",&ch);接受的是回车符号,所以那个n是一个随机的数据,你在后面再添加一个scanf("%c",&ch);就可以了!!

你没有用getchar();语句
在SCANF前加上这个句子就OK了

scanf("&