C语言小程序-----交互式计算器
这是我写的一个模拟计算器,其拥有用户交互,输入验证,报错功能,并给出了具体的解决方案。
本人c语言小白,刚学几个月,如有不足,欢迎指出。
v1.0
一般正确输入:
?选项输入错误:
?除数为0错误:
?数字输入错误:
?退出:
?
#include <stdio.h>
#include<stdlib.h>
void menu(void);//目录
char ope_ch(void);//字符检测
double num_1(void);//第一个数字检测
double num_2(void);//第二个数字检测
int main()
{
double n1;//输入的第一个数
double n2;//输入的第二个数
char ope;//输入的字符选项
char ch;//缓冲字符
menu();
ope = ope_ch();
while (ope != 'q')
{
switch (ope)
{
case 'a':
n1 = num_1();
n2 = num_2();
printf("%lf + %lf = %lf\n", n1, n2, n1 + n2);
break;
case 's':
n1 = num_1();
n2 = num_2();
printf("%lf - %lf = %f\n", n1, n2, n1 - n2);
break;
case 'm':
n1 = num_1();
n2 = num_2();
printf("%lf * %lf = %lf\n", n1, n2, n1 * n2);
break;
case 'd':
n1 = num_1();
n2 = num_2();
while (n2==0)//除数为0检测
{
printf("enter a number other than 0:\n");
n2 = num_2();
}
printf("%lf / %lf = %lf\n", n1, n2, n1 / n2);
break;
default:
printf("this ope not in the choice,pleas try again\n");
break;
}
system("pause");
system("cls");
menu();
ope = ope_ch();
}
printf("bye!\n");
printf("******************************************");
}
void menu(void)
{
printf("******************************************\n");
printf("* Enter the operation od your choice: *\n");
printf("* a.add s.subtract *\n");
printf("* m.multiply d.divide *\n");
printf("* q.quit *\n");
printf("******************************************\n");
}
double num_1(void)
{
double num1=0;
char ch;
printf("enter the first number:");
while ((scanf_s("%lf",&num1)) != 1)
{
while ((ch = getchar()) != '\n')
{
printf("\n");
putchar(ch);
printf(" is not an number.\n");
printf("pleas enter a number,such as 2.5,-1.78E8,or 3:");
}
}
return num1;
}
double num_2(void)
{
double num2=0;
char ch;
printf("enter the second number:");
while ((scanf_s("%lf",&num2)) != 1)
{
while ((ch = getchar()) != '\n')
{
printf("\n");
putchar(ch);
printf(" is not an number.\n");
printf("pleas enter a number,such as 2.5,-1.78E8,or 3:");
}
}
return num2;
}
char ope_ch(void)
{
char ch;
while ((ch=getchar()) == '\n') {
continue;
}
return ch;
}
|