请用c语言编写一个程序实现一个简单的对整数进行加减乘除和求余
时间: 2024-09-25 14:14:20 浏览: 52
当然可以,下面是一个简单的C语言程序,它创建了一个结构体来表示运算,并包含函数来执行基本的算术操作:
```c
#include <stdio.h>
// 定义运算结构体
typedef struct {
char operation; // 运算符
int num1, num2; // 操作数
} Operation;
// 函数来执行加法
int add(int a, int b) {
return a + b;
}
// 函数来执行减法
int subtract(int a, int b) {
return a - b;
}
// 函数来执行乘法
int multiply(int a, int b) {
return a * b;
}
// 函数来执行除法(返回商)
int divide(int a, int b) {
if (b != 0)
return a / b;
else
printf("Error: Division by zero is not allowed.\n");
return 0; // 如果除数为零,返回默认值
}
// 函数来执行取模(求余)
int modulo(int a, int b) {
return a % b;
}
// 主函数用于获取用户输入并显示结果
void perform_operation(Operation op) {
switch (op.operation) {
case '+':
printf("Result of addition: %d\n", add(op.num1, op.num2));
break;
case '-':
printf("Result of subtraction: %d\n", subtract(op.num1, op.num2));
break;
case '*':
printf("Result of multiplication: %d\n", multiply(op.num1, op.num2));
break;
case '/':
printf("Result of division: %d\n", divide(op.num1, op.num2));
break;
case '%':
printf("Result of modulo: %d\n", modulo(op.num1, op.num2));
break;
default:
printf("Invalid operation.\n");
}
}
int main() {
int num1, num2;
char operator_choice;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("Choose an operation (+,-,*,/,%): ");
scanf(" %c", &operator_choice);
Operation op = {operator_choice, num1, num2};
perform_operation(op);
return 0;
}
```
阅读全文