1.简单计算器。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
double a, b;
char c;
scanf("%lf %c %lf", &a, &c, &b);
switch (c)
{
case '+':
printf("%.4lf+%.4lf=%.4lf", a, b, a + b);
break;
case '-':
printf("%.4lf-%.4lf=%.4lf", a, b, a - b);
break;
case '*':
printf("%.4lf*%.4lf=%.4lf", a, b, a * b);
break;
case '/':
if (b == 0.0)
{
printf("Wrong!Division by zero!\n");
}
else
{
printf("%.4lf/%.4lf=%.4lf", a, b, a / b);
}
break;
default:
printf("Invalid operation!\n");
}
return 0;
}
2.用函数指针实现计算器。
#define _CRT_SECURE_NO_WARNINGS
#include <Stdio.h>
void menu()
{
printf("*****************************\n");
printf("***** 1.Add 2.Sub *****\n");
printf("***** 3.Mul 4.Div *****\n");
printf("****** 0.exit *****\n");
printf("*****************************\n");
}
int Add(int x,int y)
{
return x + y;
}
int Sub(int x, int y)
{
return x - y;
}
int Mul(int x, int y)
{
return x * y;
}
int Div(int x, int y)
{
return x / y;
}
void calc(int (*pf)(int, int))
{
int x = 0;
int y = 0;
int z = 0;
printf("请输入两个操作数:");
scanf("%d %d", &x, &y);
z = pf(x, y);
printf("%d\n", z);
}
int main()
{
int input = 0;
do
{
menu();
printf("请选择:");
scanf("%d", &input);
switch(input)
{
case 1:
calc(Add);
break;
case 2:
calc(Sub);
break;
case 3:
calc(Mul);
break;
case 4:
calc(Div);
break;
case 0:
printf("退出计算器\n");
break;
defalut :
printf("选择错误\n");
break;
}
} while (input);
return 0;
}
注意:运用函数指针实现的计算器并没有直接调用函数,而是主调calc函数,calc函数再回调Add,Sub,Mul,Div函数。