一道字符输入/输出的问题
本人目前在自学C primerplus,这是一道来自本书的练习题
以下是我的代码
程序代码:
#include<stdio.h> #include<ctype.h> char get_choice(); double get_number(); char get_first_char(); void main() { char ch; double first,second,ans; while((ch=get_choice())!='q') { printf("Enter first number:"); first=get_number(); printf("Enter second number:"); while((second=get_number())==0&&ch=='d') printf("Enter a number other than 0:"); switch(ch) { case 'a':ans=first+second; printf("%.1f + %.1f = %.1f\n",first,second,ans); break; case 's':ans=first-second; printf("%.1f - %.1f = %.1f\n",first,second,ans); break; case 'm':ans=first*second; printf("%.1f * %.1f = %.1f\n",first,second,ans); break; case 'd':ans=first/second; printf("%.1f / %.1f = %.1f\n",first,second,ans); break; default :printf("Systme error!"); break; } } printf("Bye."); //putchar(menu()); } char get_choice() { char ch; printf("Enter the operation of your choice:\n"); printf("a.add s.subtract\n"); printf("m.multiply d.divide\n"); printf("q.quit\n"); ch=get_first_char(); while(ch!='a'&&ch!='s'&&ch!='m'&&ch!='d'&&ch!='q') { printf("Please respond with a, s, m, d, or q.\n"); ch=get_first_char(); } return ch; } char get_first_char() { char ch; while(isspace(ch=getchar())) { if(ch=='\n') printf("No alpha received,please try again.\n"); } while(getchar()!='\n') continue; return ch; } double get_number() { double 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 as 2.5, -1,7E8, or 3:"); } return n; }
运行到读入数据的函数时发现无法读入浮点数,自己找不到问题出在哪,发帖希望大家指点一下。
谢谢!