c语言整数四则运算程序
时间: 2024-10-17 14:01:23 浏览: 55
在C语言中编写一个简单的整数四则运算(加法、减法、乘法和除法)程序,可以分为以下几个步骤:
1. 定义主函数`main()`,这是程序开始的地方。
2. 使用`scanf()`函数获取用户输入的两个整数和一个运算符,例如 `int num1, num2; char op;`.
3. 判断运算符,通常用switch case结构实现,比如:
```c
switch(op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) { // 防止除数为零的情况
result = num1 / num2;
} else {
printf("Error! Division by zero is not allowed.");
return 0;
}
break;
default:
printf("Invalid operator. Please enter either '+', '-', '*' or '/'");
return 0;
}
```
4. 打印结果,可以使用`printf()`函数显示计算后的结果,如 `printf("The result is %d\n", result);`.
5. 结束主函数 `return 0;`。
完整代码示例如下:
```c
#include <stdio.h>
int main() {
int num1, num2, result;
char op;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &op);
switch(op) {
case '+':
result = num1 + num2;
break;
case '- num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
printf("Error! Division by zero is not allowed.");
return 0;
}
break;
default:
printf("Invalid operator. Please enter either '+', '-', '*' or '/'");
return 0;
}
printf("The result of the operation is: %d\n", result);
return 0;
}
```
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)