C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 使用 switch...case 制作简单计算器的程序

使用 switch 编写简单计算器的 C 程序...case

在本例中,您将学习使用 switch 语句在 C 编程中创建一个简单的计算器。
要理解此示例,您应该了解以下C 编程 主题:
C switch 语句 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 语句。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4