| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1728 人关注过本帖
标题:请问为何此处定义 while(ch=getchar()!='\n')会出错
只看楼主 加入收藏
ljl16721424
Rank: 1
等 级:新手上路
帖 子:6
专家分:1
注 册:2016-9-10
结帖率:50%
收藏
 问题点数:0 回复次数:1 
请问为何此处定义 while(ch=getchar()!='\n')会出错
/***************显示一个菜单实现加法,减法,乘法,除法**********************/
#include<stdio.h>
#include<ctype.h>
char get_first(void);
float get_input(void);
int main()
{
 float i,j;    //定义输入的两个数字
 float sum;
 char ch;
 
 while(1)
 {

 printf("Enter the operation of your choice:\n");
 printf("a.add\t\ts.subtract\n");
 printf("m.mutiply\t\td.divide\n");
 printf("q.quit\n");

 ch=get_first();
 if(ch!='a'&&ch!='s'&&ch!='m'&&ch!='d')   //如果输入的不是a,s,m,d四个字母中的一个则结束程序
 {
   printf("Bey!\n");
   break;
 }
 printf("Enter first number:\n");          //输入第一个变量
 i=get_input();

 printf("Enter second number:\n");        //输入第二个变量
 j=get_input();

 while(ch=='s'&&j==0)                    //当其为除法时分母不能为0
 {
   printf("Enter a number other than 0:");
   j=get_input();
 }

  switch(ch)
  {
  case 'a':
      sum=i+j;                                 //实现加法运算
      printf("%4.2f+%4.2f=%4.2f\n",i,j,sum);
     break;
  case 's':                                    //实现除法运算
      sum=i/j;
      printf("%4.2f/%4.2f=%4.2f\n",i,j,sum);
      break;
  case 'm':                                   //实现减法运算
      sum=i-j;
      printf("%4.2f-%4.2f=%4.2f\n",i,j,sum);
     break;
  case 'd':                                   //实现乘法运算
      sum=i*j;
      printf("%4.2f*%4.2f=%4.2f",i,j,sum);
     break;
  default:
     break;
  }
 }
 return 0;
}

char get_first(void)                     //去除转义字符换行字符等非法输入
{
  int ch;
  while(isspace(ch=getchar()))
      ;
  while(getchar()!='\n')
      continue;
  return ch;
}

float get_input(void)                    //判断其输入的是否为数字
{
  float n;
  char ch;
  while(scanf("%f",&n)!=1)
  {
    while((ch=getchar())!='\n')
        putchar(ch);
        printf(" is not an number.\n");
        printf("Please enter a number,such ad 2.5,-1.78E8 or 3:");
  }
  while(getchar()!='\n')
      continue;
  printf("\n");
  return n;
}
上面程序执行结果是正确的但是我将char get_first(void)函数更改如下
char get_first(void)                     //去除转义字符换行字符等非法输入
{
  int ch;
  while(isspace(getchar()))
      ;
  while(ch=getchar()!='\n')
      continue;
  return ch;
}
其输出结果就会出错如下所示:这是什么情况啊???请各位指教
图片附件: 游客没有浏览图片的权限,请 登录注册

搜索更多相关主题的帖子: operation include choice Enter 
2016-12-14 20:08
marlow
Rank: 6Rank: 6
等 级:侠之大者
威 望:2
帖 子:125
专家分:419
注 册:2016-7-18
收藏
得分:0 
回复 楼主 ljl16721424
应该这样定义  while((ch=getchar())!='\n')

一切都在学习、尝试、摸索中
2016-12-14 20:11
快速回复:请问为何此处定义 while(ch=getchar()!='\n')会出错
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017926 second(s), 10 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved