[Java] 实验3参考代码

实验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 = 1
5 / 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值