C语言switch语句实现简单计算器 (不使用if-else)

本教程将引导你使用 C 语言的 switch 语句创建一个简单的计算器程序,该程序可以对两个整数执行乘法、除法和求余运算,并且不使用 ifelse 语句

以下是代码实现:c#include <stdio.h>

int main() { int num1, num2; char operator;

printf('Enter the expression (operand operator operand): ');    scanf('%d %c %d', &num1, &operator, &num2);

int result = 0; // 用于存储结果

switch (operator) {        case '*':            result = num1 * num2;            break;        case '/':            result = num2 == 0 ? 0 : num1 / num2; // 除数为零时结果为0,否则进行除法运算            break;        case '%':            result = num2 == 0 ? 0 : num1 % num2; // 除数为零时结果为0,否则进行取余运算            break;        default:            result = 0; // 无效的运算符,结果为0            break;    }

printf('Result: %d

', result);

return 0;}

代码解释:

  1. 引入头文件: #include <stdio.h> 用于输入输出操作。2. 定义变量: - num1num2 存储两个整数操作数。 - operator 存储运算符 (+, -, * /)。 - result 存储计算结果。3. 获取用户输入: 使用 scanf 函数获取表达式,包括两个操作数和运算符。4. 使用 switch 语句: - 根据 operator 的值,执行相应的操作。 - case 语句用于匹配运算符。 - 每个 case 语句块内使用三元运算符 ?: 处理除数为零的情况,避免程序错误。 - break 语句用于跳出 switch 语句,防止 fallthrough。 - default 语句处理无效的运算符。5. 输出结果: 使用 printf 函数输出计算结果。

程序运行示例:

Enter the expression (operand operator operand): 10 + 5Result: 15

这个程序演示了如何使用 C 语言的 switch 语句创建一个简单的计算器,并通过三元运算符避免了使用 ifelse 语句进行条件判断。


原文地址: https://www.cveoy.top/t/topic/udl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录