//进行加减乘除法的程序
#include<stdio.h>
#include<ctype.h>
int menu(void); //菜单函数
void clean(void); //清理多余的字符
int get_choice(void); //获取字符
float add(void); //加法函数
float subtract(void); //减法函数
float multiply(void); //乘法函数
float divide(void); //除法函数
float get_number(void); //用于加减乘函数里获取数据
float get_number_l(void);//用于除法函数里获取数据
int main(void)
{
int ch, i;
float result = 0;
float data;
while ((ch = menu()) != 'q')
{
int k = 1;
int i = 1;
switch (ch)
{
case 'a':
result = add();
break;
case 's':
result = subtract();
break;
case 'm':
result = multiply();
break;
case 'd':
result = divide();
break;
default:
break;
}
if((data = result - (int)result)!=0) //处理整数与浮点数的情况
printf("The calculation result is: %.4f\n\n",result);
else
printf("The calculation result is: %d\n\n", (int)result);
}
printf("\nBye!\n");
return 0;
}
int menu(void) //菜单函数
{
int ch;
printf("Enter the operation of your choice: \n");
printf("a. add\t\ts. subtract\nm. multiply\t\td. divide\nq. quit\n"); //显示菜单选项
ch = get_choice();
if (ch != 'a' && ch != 's' && ch != 'm' && ch != 'd' && ch != 'q')
{
printf("Please enter a ture choice: ");
ch = get_choice();
}
return ch;
}
int get_choice(void)
{
char ch;
scanf_s(" %c", &ch);
clean();
return ch;
}
void clean(void)
{
while (getchar() != '\n')
continue;
}
float get_number(void)
{
float ch;
char i;
while (scanf_s("%f", &ch) != 1)
{
while ((i = getchar()) != '\n')
putchar(i);
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3: ");
}
return ch;
}
float get_number_l(void)
{
float ch;
char i;
while (scanf_s("%f", &ch) != 1 ||ch==0)
{
while ((i=getchar()) != '\n')
putchar(i);
if (ch == 0)
{
printf("Enter a number other than 0: ");
continue;
}
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3: ");
}
return ch;
}
float add(void) //加法函数
{
float ch_1, ch_2;
float result;
printf("Enter first number: ");
ch_1 = get_number();
printf("Enter second number: ");
ch_2 = get_number();
result = ch_1 + ch_2;
return result;
}
float subtract(void) //减法函数
{
float ch_1, ch_2;
float result;
printf("Enter first number: ");
ch_1 = get_number();
printf("Enter second number: ");
ch_2 = get_number();
result = ch_1 - ch_2;
return result;
}
float multiply(void) //乘法函数
{
float ch_1, ch_2;
float result;
printf("Enter first number: ");
ch_1 = get_number();
printf("Enter second number: ");
ch_2 = get_number();
result = ch_1 * ch_2;
return result;
}
float divide(void) //除法函数
{
float ch_1, ch_2;
float result;
printf("Enter first number: ");
ch_1 = get_number_l();
printf("Enter second number: ");
ch_2 = get_number_l();
result = ch_1 / ch_2;
return result;
}
测试结果:
//初学者分享,如有问题请多多指出,可以进行交流,谢谢。