编写一个程序,显示一个菜单,为您提供加法、减法、乘法或除法的选项。获得您的选择后,该程序请求两个数,然后执行您选择的操作。该程序应该只接受它所提供的菜单选项。它应该使用floast类型的数,并且入股用户未能输入数字应允许其重新输入。在除法的情况中,如果用户输入0作为第二个数,该程序应该提示用户输入一个新的值。
#include <stdio.h>
#include <windows.h>
char get_choice(void);
char get_first(void);
double panduan(void);
double panduan2(void);
int main(void)
{
int choice;
double x, y, ans;
x = y = ans = 0.00;
while ((choice = get_choice()) != 'q')
{
x = panduan();
y = panduan2();
switch (choice)
{
case 'a': ans = x + y; printf("%.2f + %.2f = %.2f.\n", x, y, ans); break;
case 's': ans = x - y; printf("%.2f - %.2f = %.2f.\n", x, y, ans); break;
case 'm': ans = x * y; printf("%.2f * %.2f = %.2f.\n", x, y, ans); break;
case 'd': ans = x / y; printf("%.2f / %.2f = %.2f.\n", x, y, ans); break;
}
}
}
char get_choice(void)
{
int 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();
while (!(ch == 'a' || ch == 's' || ch == 'm' || ch == 'd') && ch != 'q')
{
printf("Please enter 'a','s','m','d','q' .\n");
ch = get_first();
}
printf("Bye.\n");
system("pause");
return ch;
}
char get_first(void)
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}
double panduan(void)
{
char ch;
double x;
printf("Enter first number: ");
while ((scanf_s("%lf", &x)) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch);
printf(" is not an integer.\nPlease enter an integer value, such as 25, -175, or 3: ");
}
return x;
}
double panduan2(void)
{
char ch;
double y;
printf("Enter second number: ");
while ((scanf_s("%lf", &y)) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch);
printf(" is not an integer.\nPlease enter an integer value, such as 25, -175, or 3: ");
}
return y;
}