中易网

C语言 初学 构造一个计算器

答案:1  悬赏:20  
解决时间 2021-04-28 08:11
  • 提问者网友:晨熙污妖王
  • 2021-04-27 23:00
#include <stdio.h> int add(int x, int y); int sub(int x, int y); int mul(int x, int y); int div(int x, int y); void compute(int x,int y,char op); //添加函数声明 int main(void) { int a, b, c; char op; scanf("%d%c%d", &a, &op, &b); switch(op) { case '+': c = compute(a, b, add); break; case '-': c = compute(a, b, sub); break; case '*': c = compute(a, b, mul); break; case '/': c = compute(a, b, div); break; } printf("%d%c%d=%d\n", a, op, b, c); return 0; } //添加声明函数的定义(既函数首部及函数体) void compute(int x,int y,char op) { switch(op) { case '+': add(x,y); case '-': sub(x,y); case '*': mul(x,y); case '/': div(x,y); } } 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; } 初学 运行不了 请大神指出错误!!!
最佳答案
  • 二级知识专家网友:末路丶一枝花
  • 2021-04-28 00:27
#include <stdio.h>

int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
int compute(int x,int y,char op);
//添加函数声明

int main(void)
{
int a, b, c;
char op;
scanf("%d%c%d", &a, &op, &b);
switch(op)
{
case '+':
c = compute(a, b, '+');//这不能写add。这样会认为是add这个函数的指针,你这个函数原先是返回void,却要赋值给c.
break;
case '-':
c = compute(a, b, '-');
break;
case '*':
c = compute(a, b, '*');
break;
case '/':
c = compute(a, b, '/');
break;
}
printf("%d%c%d=%d\n", a, op, b, c);
return 0;
}

//添加声明函数的定义(既函数首部及函数体)
int compute(int x,int y,char op)
{
switch(op)
{
case '+':
 return add(x,y);
case '-':
return sub(x,y);
case '*':
return mul(x,y);
case '/':
return div(x,y);
}
return 0;
}

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;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息