0%

模拟-四舍五入打印

题目

输入

1
2
3
4
5
6
7
8
7
80
92
56
74
88
99
10

输入

1
2
3
99
10
71.29

分析:主要就是java中如何四舍五入打印浮点数

1
2
3
4
import java.text.DecimalFormat
double a = 123.121323232;
DecimalFormat df = new DecimalFormat("0.00") //四舍五入打印两位小数,并且要保留最后的0,比如0.80要按0.80打印,不能按0.8打印

另外一个隐藏的易错点就是java中两个int型计算还是int,要得到java必须把其中之一强转成double或乘个1.0也成double型

代码

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
import java.util.Scanner;
import java.text.DecimalFormat;

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int highestScore = 0;
int lowestScore = 100;
int totalScore = 0;
for(int i = 0; i < n; i++) {
int score = scan.nextInt();
totalScore += score;
if(score < lowestScore) lowestScore = score;
if(score > highestScore) highestScore = score;
}
System.out.println(highestScore);
System.out.println(lowestScore);
DecimalFormat df = new DecimalFormat("0.00");
double averageScore = (double)totalScore / n;
String rounded_num = df.format(averageScore);
System.out.println(rounded_num);
scan.close();
}
}