20192319 2020-2021-1 《数据结构与面向对象程序设计》实验二报告

实验二报告

  • 课程:《程序设计与数据结构》
  • 班级: 1923
  • 姓名: 李歆韵
  • 学号:20192319
  • 实验教师:王志强
  • 实验日期:2020年10月8日
  • 必修/选修: 必修

1.实验内容

(一)实验内容

  • (1) 编写简单的计算器,完成加减乘除模运算。
  • (2) 要求从键盘输入两个数,使用判定语句选择一种操作,计算结果后输出,然后使用判定和循环语句选择继续计算还是退出。
  • (3) 编写测试代码,测试验证。( https://www.cnblogs.com/rocedu/p/4472842.html

2. 实验过程及结果

2.1 编写简易计算器代码

import java.util.*;

public class SimpleCal{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char d;//用于判断是否继续
do {
System.out.print("Please input a number: ");
double a = scanner.nextDouble();//输入数字
System.out.print("Please input another number: ");
double b = scanner.nextDouble();
System.out.println("Choose the way of calculation:\n\t1 for addition.\n\t2 for subtraction.\n\t3 for multiply.\n\t4 for division.\n\t5 for module.");
System.out.print("You choose: ");
int c = scanner.nextInt();//选择运算方式
while (b == 0 && c == 4 || b == 0 && c == 5) {
System.out.println("Invalid calculation,please correct the numbers.");
System.out.print("Please input a number: ");
a = scanner.nextDouble();
System.out.print("Please input another number: ");
b = scanner.nextDouble();
}//排除运算无意义的情况

double result = Cal(a, b, c);//用子函数进行运算
System.out.println("The result is " + result);
System.out.print("Do you want to continue the calculation?(y/n) ");//使用条件语句判断是否继续
d = scanner.next().charAt(0);
} while (d == 'y');
System.out.println("The calculation is over.");
}

public static double Cal(double a, double b, int c) {//子函数进行运算
double d = 0.0;
switch (c) {
case 1:
d = a + b;
break;
case 2:
d = a - b;
break;
case 3:
d = a * b;
break;
case 4:
d = a / b;
break;
case 5:
d = a % b;
break;
}
return d;
}
}

2.2 运行结果


2.3 测试代码

public class SimpleCalText {
public static void main(String[] args){
double result=0.0;
result = SimpleCal.Cal(7,4,1);
if (result11)
System.out.println("Pass 1");
else System.out.println("Wrong 1");
result = SimpleCal.Cal(7,4,2);
if (result
3)
System.out.println("Pass 2");
else System.out.println("Wrong 2");
result = SimpleCal.Cal(7,4,3);
if (result28)
System.out.println("Pass 3");
else System.out.println("Wrong 3");
result = SimpleCal.Cal(16,4,4);
if (result
4)
System.out.println("Pass 4");
else System.out.println("Wrong 4");
result = SimpleCal.Cal(7,4,5);
if (result==3)
System.out.println("Pass 5");
else System.out.println("Wrong 5");
}
}

2.4 测试结果

2.5 上传码云

3. 实验过程中遇到的问题和解决过程

  • 问题1:在判断是否继续时输入先于文字提示出现
  • 问题1解决方案:将System.out.print("Do you want to continue the calculation?(y/n) ");d = scanner.next().charAt(0);位置互换。

其他(感悟、思考等)

  • 本次实验代码的思路与上学期程序设计基础所学的条件与循环和子函数相同,以后要多注意融会贯通。
  • 本次测试代码使用的是main函数,编写较为冗长。

参考资料

posted on 2020-10-09 09:42  节奏阿莱士  阅读(145)  评论(0)    收藏  举报

导航