我在执行类似任务时遇到问题。
这是任务:
这是我的代码:
import java.text.DecimalFormat;
import java.util.Scanner;
public class MinMaxSumAverage {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#0.00");
Scanner scanner = new Scanner(System.in);
double average;
double sum = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double numbers = scanner.nextInt();
for (int i = 0; i < numbers; ++i) {
int num = scanner.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
average = sum / numbers;
System.out.println("min=" + (df.format(min)));
System.out.println("max=" + (df.format(max)));
System.out.println("sum=" + (df.format(sum)));
System.out.println("avg=" + (df.format(average)));
}
}
It work correct, but in "judge system" who test my code have some errors:
您能帮我找出我的代码有什么问题吗?
编辑: 我将总和,最大值和最小值从double更改为int,并且测试结果的变化很小:
测试2:
答案 0 :(得分:2)
您的代码无法接受十进制输入,这就是为什么您收到InputMismatchException
的原因。更改此行
int num = scanner.nextInt();
到
double num = scanner.nextDouble();