选择结构程序设计实验:身高预测

来源:互联网 发布:手术室护士必知的知识 编辑:程序博客网 时间:2024/04/29 15:25

上周作实验,时选择类结构程序设计,在输入时出现自动跳过的BUG,后来经查证时因为scanf("%c",  )读取了的键盘缓冲区中上一语句用来结束输入的回车符。

Code:
  1. #include<stdio.h>   
  2. #include<stdlib.h>   
  3.   
  4. int main(void)   
  5. {   
  6.     char sex=0,sports=0,diet=0;   
  7.     int faHeight,moHeight;   
  8.     double height,fh,mh ;   
  9.   
  10.     printf("enter moHeight(cm):");   
  11.     scanf("%d",&moHeight);   
  12.     printf("enter faHeight(cm):");   
  13.     scanf("%d",&faHeight);   
  14.     printf("enter kid's sex(f(girl) or m(boy)):");   
  15.     getchar();               //用getchar()读取键盘缓冲区的回车字符,防止scanf()自动读取造成出错
  16.     scanf("%c",&sex);   
  17.     printf("enter kid's sports(y or n):");   
  18.     getchar();               //用getchar()读取键盘缓冲区的回车字符,防止scanf()自动读取造成出错
  19.     scanf("%c",&sports);   
  20.     printf("enter kid's diet(y or n):");   
  21.     getchar();               //用getchar()读取键盘缓冲区的回车字符,防止scanf()自动读取造成出错
  22.     scanf("%c",&diet);   
  23.   
  24.     switch(sex){   
  25.   
  26.         case 'm':{   
  27.             mh=(faHeight+moHeight)*0.54;               
  28.             if((sports=='y')&&(diet=='y')){   
  29.                 height=mh*1.02*1.015;   
  30.             }   
  31.             else if(sports=='y'){   
  32.                 height=mh*1.02;   
  33.             }   
  34.             else if(diet=='y'){   
  35.                 height=mh*1.015;   
  36.             }   
  37.             else{   
  38.                 height=mh;   
  39.             }   
  40.         }   
  41.         case 'f': {   
  42.             fh=(faHeight*0.923+moHeight)/2.0;   
  43.             if((sports=='y')&&(diet=='y')){   
  44.                 height=fh*1.02*1.015;   
  45.             }   
  46.             else if(sports=='y'){   
  47.                 height=fh*1.02;   
  48.             }   
  49.             else if(diet=='y'){   
  50.                 height=fh*1.015;   
  51.             }   
  52.             else {   
  53.                 height=fh;   
  54.             }      
  55.         }   
  56.     }   
  57.     printf("the kid's height is : %.2f cm/n",height);   
  58.     system("pause");   
  59.   
  60.   
  61.     return 0;   
  62.   
  63.   
  64. }  

 

原创粉丝点击