c语言设计一个计算器,支持7种计算方法
时间: 2024-10-08 17:15:03 浏览: 84
在C语言中设计一个简单的计算器,支持加减乘除以及取模、平方根、幂运算和求绝对值这七种基本数学操作,可以采用结构体来封装每种运算,并结合函数实现。下面是一个基础的示例:
```c
#include <stdio.h>
#include <math.h>
// 定义计算器的结构体
typedef struct Calculator {
double (*operation)(double, double);
} Calculator;
// 运算函数指针
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) { if (b != 0) return a / b; else return -1; } // 避免除数为零的情况
double modulo(double a, double b) { return fmod(a, b); }
double square_root(double a) { if (a >= 0) return sqrt(a); else return -1; }
double power(double base, double exponent) { return pow(base, exponent); }
double absolute_value(double num) { return abs(num); }
// 主函数
int main() {
Calculator calc[] = {
{add},
{subtract},
{multiply},
{divide},
{modulo},
{square_root},
{power},
{absolute_value}
};
int choice;
printf("选择运算方法:\n");
printf("1. 加法\n2. 减法\n3. 乘法\n4. 除法\n5. 取模\n6. 平方根\n7. 幂运算\n8. 绝对值\n");
scanf("%d", &choice);
if (choice >= 1 && choice <= 8) {
double num1, num2;
printf("请输入两个数字: ");
scanf("%lf %lf", &num1, &num2);
switch (choice - 1) {
case 0: printf("%.2f + %.2f = %.2f\n", num1, num2, (*(calc[0]))(num1, num2)); break;
case 1: printf("%.2f - %.2f = %.2f\n", num1, num2, (*(calc[1]))(num1, num2)); break;
case 2: printf("%.2f * %.2f = %.2f\n", num1, num2, (*(calc[2]))(num1, num2)); break;
case 3: printf("%.2f / %.2f = %.2f\n", num1, num2, (*(calc[3]))(num1, num2)); break;
case 4: printf("%.2f %%%%lf = %.2f\n", num1, num2, (*(calc[4]))(num1, num2)); break;
case 5: printf("%.2f 的平方根 ≈ %.2f\n", num1, (*(calc[5]))(num1)); break;
case 6: printf("%.2f 的幂 %.2f = %.2f\n", num1, num2, (*(calc[6]))(num1, num2)); break;
case 7: printf("%.2f 的绝对值 = %.2f\n", num1, (*(calc[7]))(num1)); break;
}
} else {
printf("无效的选择。\n");
}
return 0;
}
阅读全文