练习9-数据计算

题目

写一个简单的函数实现下面的功能:具有三个参数,完成对两个整型数据的加、减、乘、除四种操作,前两个为操作数,第三个参数为字符型的参数。

解题步骤

(1)定义变量;
(2)接收用户输入;
(3)函数计算;
(4)输出结果;

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;

public class E20210814 {
public static void main(String[] args) {
int a1, b;
char c;
Scanner input = new Scanner(System.in);
System.out.print("please enter two whole numbers:");
a1 = input.nextInt();
b = input.nextInt();
System.out.print("please enter your computing type:[a-addition s-subtraction m-multiplication d-division]:");
c = input.next().charAt(0);
switch (c) {
case 'a' -> System.out.format("%d+%d=%d", a1, b, a1 + b);
case 's' -> System.out.format("%d-%d=%d", a1, b, a1 - b);
case 'm' -> System.out.format("%d*%d=%d", a1, b, a1 * b);
case 'd' -> {
if (b == 0) {
System.out.println("the divisor is not 0 error!!!");
} else {
System.out.format("%d/%d=%d", a1, b, a1 / b);
}
}
default -> System.out.println("input error please try again!!!");
}
}
}

enhanced switch

1
2
3
4
5
6
7
8
9
10
11
12
13
switch (c) {
case 'a' -> System.out.format("%d+%d=%d", a1, b, a1 + b);
case 's' -> System.out.format("%d-%d=%d", a1, b, a1 - b);
case 'm' -> System.out.format("%d*%d=%d", a1, b, a1 * b);
case 'd' -> {
if (b == 0) {
System.out.println("the divisor is not 0 error!!!");
} else {
System.out.format("%d/%d=%d", a1, b, a1 / b);
}
}
default -> System.out.println("input error please try again!!!");
}

说明

  1. 注意switch-case语句中case处的数据类型,因为设定了变量cchar类型,所以需要使用 c = input.next().charAt(0) 语句接收用户键盘上的单个字符输入,charAt() 方法用于返回指定索引处的字符,索引范围为从 0 到 length() - 1
  2. Java 中引入增强型switch结构,给出参考代码。主要特点如下:需要返回值、无需 break、使用箭头->、可进行 case 间的合并,以逗号分隔。

C语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>

int calculate(int operand1, int operand2, char type)
{
char a, s, m, d;
switch (type)
{
case 'a':
printf("%d+%d=%d", operand1, operand2, operand1 + operand2);
break;
case 's':
printf("%d-%d=%d", operand1, operand2, operand1 - operand2);
break;
case 'm':
printf("%d*%d=%d", operand1, operand2, operand1 * operand2);
break;
case 'd':
{
if (operand2 == 0)
{
printf("the divisor is not 0 the error please try again");
break;
}

else
{
printf("%d/%d=%d", operand1, operand2, operand1 / operand2);
break;
}
}
default:
printf("if the type of operation is not specified please re enter!!!");
}
}

int main()
{
int a, b;
char c;
printf("please enter two integers:");
scanf("%d%d", &a, &b);
printf("please enter your computing type:[a-addition s-subtraction m-multiplication d-division]:");
getchar();
scanf("%c", &c);
calculate(a, b, c);
return 0;
}

说明

因为有四种计算类型,所以我们使用switch-case语句解决,注意除法计算中除数不为 0 的条件判断,且case后需为常量,这里使用字符做判断条件,加上单引号‘’变为字符常量。