c语言实现多功能计算器进行四则运算,阶乘,矩阵,平方根,求幂,进制转换等其他运算,可以复位,报错,退出,运算式子从文件输入程序,程序运算后再将答案输入文件
时间: 2024-06-15 16:04:23 浏览: 73
C语言可以实现一个多功能计算器,可以进行四则运算、阶乘、矩阵运算、平方根、求幂、进制转换等其他运算。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <math.h>
// 四则运算函数
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 {
printf("Error: Division by zero!\n");
return 0;
}
}
// 阶乘函数
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// 平方根函数
double squareRoot(double num) {
if (num >= 0) {
return sqrt(num);
} else {
printf("Error: Invalid input for square root!\n");
return 0;
}
}
// 求幂函数
double power(double base, double exponent) {
return pow(base, exponent);
}
// 进制转换函数
void decimalToBinary(int decimal) {
int binary[32];
int i = 0;
while (decimal > 0) {
binary[i] = decimal % 2;
decimal = decimal / 2;
i++;
}
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
}
int main() {
int choice;
double num1, num2;
int num;
char operator;
while (1) {
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("5. Factorial\n");
printf("6. Square Root\n");
printf("7. Power\n");
printf("8. Decimal to Binary\n");
printf("9. Reset\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2lf\n", add(num1, num2));
break;
case 2:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2lf\n", subtract(num1, num2));
break;
case 3:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2lf\n", multiply(num1, num2));
break;
case 4:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2lf\n", divide(num1, num2));
break;
case 5:
printf("Enter a number: ");
scanf("%d", &num);
printf("Result: %d\n", factorial(num));
break;
case 6:
printf("Enter a number: ");
scanf("%lf", &num1);
printf("Result: %.2lf\n", squareRoot(num1));
break;
case 7:
printf("Enter base and exponent: ");
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2lf\n", power(num1, num2));
break;
case 8:
printf("Enter a decimal number: ");
scanf("%d", &num);
decimalToBinary(num);
break;
case 9:
// 重置操作
break;
case 0:
// 退出程序
return 0;
default:
printf("Invalid choice!\n");
}
}
return 0;
}
```
这个示例代码实现了一个简单的多功能计算器,可以根据用户的选择进行不同的运算。用户可以输入两个数进行四则运算,输入一个数进行阶乘、平方根、求幂等运算,输入一个十进制数进行二进制转换。你可以根据自己的需求进行修改和扩展。
阅读全文