[Java] 实验3参考代码

来源:互联网 发布:临猗数据恢复 编辑:程序博客网 时间:2024/05/29 04:45

实验3月20日晚截止,实验截止后将在此给出参考代码。


求平方根

double res = Math.sqrt(num);// Math.sqrt(num)用来求num的平方根// res是作为result的缩写// 将result定义成double而非int类型:int类型无法表示浮点数。

代码:

import java.util.Scanner;public class Sqrt {public static void main(String args[]) {Scanner in = new Scanner(System.in);double num = in.nextDouble();System.out.println(Math.sqrt(num));}}


华氏温度转换为摄氏温度

整数 除 整数,获得的仍为整数:

10 / 9 = 15 / 9 = 0

注意到,不同的机器,浮点的精度可能不同,这会导致在输出结果时,小数点后最后一位与答案不同。

大家可以放心提交,因为最终你的代码将在服务器端运行,而不是你本地的机器,这样输出的值一般就是相同的了。

代码:

import java.util.Scanner;public class Temperature {public static void main(String[] args) {Scanner in = new Scanner(System.in);double f = in.nextDouble();double c = 5d / 9 * (f - 32);System.out.println("The temperature is " + c); // The word "temperature" is different from the one in the 10.77.30.33}}


求旅行时间

输入2个整数time1和time2,表示火车的出发时间和到达时间,计算并输出旅途时间。

有效的时间范围是0000到2359,不需要考虑出发时间晚于到达时间的情况。

例:括号内是说明

输入

712 1411(出发时间是7:12,到达时间是14:11)

输出

The train journey time is 6 hrs 59 mins.

import java.util.Scanner;public class TravelTime {public static void main(String[] args) {Scanner in = new Scanner(System.in);int time1 = in.nextInt();int time2 = in.nextInt();time1 = time1 / 100 * 60 + time1 % 100;time2 = time2 / 100 * 60 + time2 % 100;System.out.println("The train journey time is "+ (time2 - time1) / 60 + " hrs "+ (time2 - time1) % 60 + " mins.");}}


0 0
原创粉丝点击