gpt4 book ai didi

java - 为 double 打印 3 个十进制数

转载 作者:行者123 更新时间:2023-12-02 11:56:14 24 4
gpt4 key购买 nike

我应该找到一堆给定数字的平均值,然后将它们全部相加,然后除以给我的数字数量,平均值必须有 3 位小数,所以不是 45.0,而是 45.000,我的可以工作,但前提是最后一个数字不为 0。

import java.util.Scanner;
import static java.lang.System.*;

public class Average
{
private String line;
private double average, sum, count;

public Average()
{
setLine("");
}

public Average(String s)
{
setLine(s);
}

public void setLine(String s)
{
line = s;
sum = 0.0;
count = 0.0;
average = 0.0;
}

public double getCount()
{
int num = 0;
while(num<line.length())
{
if(line.charAt(num) == 32)
{
count ++;
num ++;
}
else
num ++;
}
count ++;
return count;
}

public double getSum()
{
Scanner bobby = new Scanner(line);
while(bobby.hasNextInt())
sum = sum + bobby.nextInt();
return sum;
}

public double getAverage()
{
average = getSum()/getCount();
average = average*1000;
if(average%10>4)
{
average = Math.floor(average);
average ++;
average = average/1000.0;
}
else
{
average = Math.floor(average);
average = average/1000.0;
}
return average;
}

public String getLine()
{
return line;
}

public String toString()
{
return "";
}
}

这是我的运行者文件

import java.util.Scanner;
import static java.lang.System.*;

public class AverageRunner
{
public static void main( String args[] )
{
String s = "9 10 5 20";
Average bob = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob.getAverage());
System.out.println();

s = "11 22 33 44 55 66 77";
Average bob1 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob1.getAverage());
System.out.println();

s = "48 52 29 100 50 29";
Average bob2 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob2.getAverage());
System.out.println();

s = "0";
Average bob3 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob3.getAverage());
System.out.println();

s = "100 90 95 98 100 97";
Average bob4 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob4.getAverage());
}
}

最佳答案

使用DecimalFormat:

DecimalFormat df = new DecimalFormat("#.000"); 
System.out.println("Nummber: " + df.format(1.2345));

关于java - 为 double 打印 3 个十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47582056/

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