gpt4 book ai didi

java - Java-仅显示两个小数点?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:57 25 4
gpt4 key购买 nike

这个问题已经有了答案:
How to display an output of float data with 2 decimal places in Java?
16个答案
所以我的程序也做了我想做的一切,除了当随机数为temps生成时,只显示小数点后2位(12.00)。它现在正在做的是(12.1234567897654)。
我是一个Java初学者,这是我自己完成的第一个程序,所以如果答案很明显,请不要吝啬:
我试过printf和%.2f,但我没法用

public class ArrayOfTemperatures
{
public static void main(String[] args)
{

double [] temp = new double [7];


double random = Math.random() * 100 + 1;

temp[0] = Math.random() * 100 + 1;

//Calculating average
int sum = 0;
for (int i = 0; i < temp.length; i++) {
temp[i] = Math.random() * 100 + 1;
sum += temp[i];
}

//average being stated
double average = (double) sum / temp.length;
System.out.println("The average temperature is " + average);

//Temperatures
for (int i = 0; i < temp.length; i++) {
temp[i] = Math.random() * 100 + 1;
System.out.print("Temperature " + (i + 1) + " is: " + temp[i]);
if (temp[i] > average){
System.out.println(" and is above average.");
}
else {
System.out.println(" and is below average.");
}


}

}
}

输出示例如下:
The average temperature is 42.714285714285715
Temperature 1 is: 14.71803486458223 and is below average.
Temperature 2 is: 33.10321474550992 and is below average.
Temperature 3 is: 18.661262675746727 and is below average.
Temperature 4 is: 82.12893152205741 and is above average.
Temperature 5 is: 90.97086140892438 and is above average.
Temperature 6 is: 19.609064446916477 and is below average.
Temperature 7 is: 75.47742502105827 and is above average.

最佳答案

您可以使用format函数。基本上,它和printf一样。尝试

System.out.println(String.format("Temperature %d is: %.2f", i + 1, temp[i]));

关于java - Java-仅显示两个小数点? ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com