C语言使用switch...case实现简单计算器的程序

要理解这个示例,您应该了解以下 C 编程 主题


此程序从用户那里获取一个算术运算符+, -, *, /和两个操作数。然后,它根据用户输入的运算符对两个操作数执行计算。


使用 switch 语句的简单计算器

#include <stdio.h>

int main() {

  char op;
  double first, second;
  printf("Enter an operator (+, -, *, /): ");
  scanf("%c", &op);
  printf("Enter two operands: ");
  scanf("%lf %lf", &first, &second);

  switch (op) {
    case '+':
      printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
      break;
    case '-':
      printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
      break;
    case '*':
      printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
      break;
    case '/':
      printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
      break;
    // operator doesn't match any case constant
    default:
      printf("Error! operator is not correct");
  }

  return 0;
}

输出

Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

用户输入的*运算符存储在op中。而两个操作数1.54.5分别存储在firstsecond中。

由于运算符*匹配case '*':,因此程序控制跳转到

printf("%.1lf * %.1lf = %.1lf", first, second, first * second);

此语句计算乘积并将其显示在屏幕上。

为了使我们的输出看起来更整洁,我们使用代码%.1lf将输出限制为一位小数。

最后,break;语句结束switch语句。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战