用c语言编写一个计算器,实现的功能有:四则运算,带括号的运算,对数指数运算,三角函数运算
时间: 2024-04-10 18:28:33 浏览: 18
你可以使用C语言编写一个简单的计算器来实现这些功能。以下是一个基本的示例:
```c
#include <stdio.h>
#include <math.h>
// 计算器函数声明
float calculate(char operator, float operand1, float operand2);
int main() {
char operator;
float operand1, operand2, result;
printf("请输入运算符(+、-、*、/):");
scanf("%c", &operator);
printf("请输入操作数1:");
scanf("%f", &operand1);
printf("请输入操作数2:");
scanf("%f", &operand2);
result = calculate(operator, operand1, operand2);
printf("结果:%f\n", result);
return 0;
}
// 计算器函数定义
float calculate(char operator, float operand1, float operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
printf("无效的运算符\n");
return 0;
}
}
```
这是一个简单的计算器,可以进行四则运算。你可以在此基础上添加其他功能,如带括号的运算、对数指数运算和三角函数运算。对于这些功能,你可以使用相应的C库函数,如`math.h`中的`log()`和`sin()`等函数来实现。