标题:c primer plus 第8章第8题:
只看楼主
qdg008
Rank: 2
等 级:论坛游民
帖 子:9
专家分:10
注 册:2011-8-25
结帖率:100%
 问题点数:0 回复次数:1 
c primer plus 第8章第8题:
//为什么在菜单选择时,模拟错误录入:两个空格加a再回车,程序没有反映,再按回车程序才响应。不解中,高人来指点。
#include <stdio.h>
#include <ctype.h>
#define GF1 printf("Enter first number:")
#define GF2 printf("Enter second number:")
char getchoice(void);
void showmenu(void);
float get_f(void);
char getfirst(void);
int main(void)
{
    char choice;
    float i1,i2;
    showmenu();
    while((choice=getchoice())!='q')
    {
        switch(choice)
        {
            case 'a':GF1; i1=get_f();
                     GF2; i2=get_f();
                     printf("%.1f+%.1f=%.1f\n",i1,i2,i1+i2);    break;
            case 's':GF1; i1=get_f();
                     GF2; i2=get_f();
                     printf("%.1f-%.1f=%.1f\n",i1,i2,i1-i2);    break;
            case 'm':GF1; i1=get_f();
                     GF2; i2=get_f();
                     printf("%.1f * %.1f=%.1f\n",i1,i2,i1*i2);   break;
            case 'd':GF1; i1=get_f();
                     GF2; i2=get_f();
                     while(!i2)
                      {
                          printf("Enter a number other than 0:");
                          i2=get_f();
                      }
                      printf("%.1f/%.1f=%.1f\n",i1,i2,i1/i2);    break;
            default:puts("Please get the choice about a,s,m,d or q:");
        }
        showmenu();
    }
    return 0;
}
char getchoice(void)
{
    char ch;
    ch=getfirst();
    while(ispunct(ch))
    {
        ch=getfirst();
        puts("Please get the choice about a,s,m,d or q:");
    }
    while(getchar()!='\n')
        continue;
    return ch;
}
void showmenu(void)
{
    printf("Enter the operation of your choice:\n"
           "============================\n"
           "a.加                s.减\n"
           "m.乘                d.除\n"
           "q.退出\n"
           "============================\n");
}
float get_f(void)
{
    float f;
    char ch;
    while((scanf("%f",&f)!=1))
      {
          while((ch=getchar())!='\n')
             putchar(ch);
        printf(" is not an number.\n");
        printf("Please enter a number,such as 2.5,-178E8,or 3:");
       }
    return f;
}
char getfirst(void)
{
    char ch;
    ch=getchar();
    while(isspace(ch))
        ch=getchar();
    while(getchar()!='\n')
        continue;
    return ch;
}
 
搜索更多相关主题的帖子: number include void choice 
2012-07-17 23:23
qdg008
Rank: 2
等 级:论坛游民
帖 子:9
专家分:10
注 册:2011-8-25
得分:0 
额!
char getchoice(void)函数好像是多余了。
while((choice=getchoice())!='q')
改为while((choice=getfirst())!='q')后,程序运行成功。
2012-07-18 00:02



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-373599-1-1.html




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

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