|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <ctype.h>
void menu(void);
char get_choice(void);
char get_first(void);
float get_float(void);
int main(void)
{
char choice;
float num1 = 0, num2 = 0;
menu();
while ((choice = get_choice()) != 'q')
{
printf("Enter first number:");
num1 = get_float();
printf("Enter second number:");
num2 = get_float();
while (num2 == 0 && choice == 'd')
{
printf("Please enter another number without 0.\n");
num2 = get_float();
}
switch (choice)
{
case 'a':
printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
break;
case 's':
printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
break;
case 'm':
printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);
break;
case 'd':
printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
break;
default:
printf("Quit!\n");
break;
}
}
printf("Bye!\n");
getchar();
return 0;
}
void menu(void)
{
printf("Enter the operation of your choice:\n");
printf("a.add s.subtract\n");
printf("m.multiply d.divide\n");
printf("q.quit\n");
}
char get_choice(void)
{
char ch;
ch = get_first();
while (ch != 'a' && ch != 's' && ch != 'm' && ch != 'd' && ch != 'q')
{
printf("Please response with a,s,m,d or q.\n");
ch = get_first();
}
return ch;
}
char get_first(void)
{
int input;
while(isspace(input = getchar()));
while (getchar() != '\n')
continue;
return input;
}
float get_float(void)
{
int num ,ch;
while ((scanf_s("%f", &num)) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch);
printf(" is not an number.\n");
printf("Please enter a number 4, such as 2.5, -1.78E8, or 3:");
}
return num;
}
为什么num1和num2读取的scanf会错误
本帖最后由 tianyuan 于 2019-4-19 17:02 编辑
float get_float(void)
{
int num ,ch; //应该是folat num; 和 char ch;
while ((scanf_s("%f", &num)) != 1) //这里是%f,那么num也要是float类型。float和Int 在内存里存储格式是不一样的
{
while ((ch = getchar()) != '\n')
putchar(ch);
printf(" is not an number.\n");
printf("Please enter a number 4, such as 2.5, -1.78E8, or 3:");
}
return num;
}
char get_first(void) 这个函数的返回值类型是char
{
int input; 而你这里声明为int,虽然你运行后的结果没有问题,但是不要犯这种错
while(isspace(input = getchar()));
while (getchar() != '\n')
continue;
return input;
}
|
|