gpt4 book ai didi

java - 行星超出了数字框

转载 作者:行者123 更新时间:2023-11-30 03:45:33 27 4
gpt4 key购买 nike

我在使用以下代码时遇到问题:

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

double planets = 840000;
double numofsun = 2.5;
double total = 0;

System.out.println("Galaxy #"+"\t"+"Planets");

for(int i=1;i<12;i++){
double siSky= planets * numofsun;
total+=siSky;
System.out.println(i+"\t"+total);
}
}
}

该程序旨在计算给定星系内的行星数量,但问题似乎是一旦行星数量达到数百万和数十亿,它就会开始输出如下数字:

5       1.05E7                                                                                                      
6 1.26E7
7 1.47E7
8 1.68E7
9 1.89E7
10 2.1E7
11 2.31E7

我不知道应该用什么来代替 double 来实现此目的。

还可以显示逗号,例如:1,200,000,000

我最终会添加更多列,但我必须正确设置这些列,以便其他列中的数字不会显得那么奇怪。

最佳答案

使用长数字,而不是整数,并使用使用分组的 DecimalFormat 对象。例如,

import java.text.DecimalFormat;

public class Foo {
private static final String FORMAT_STRING = "0";

public static void main(String[] args) {
DecimalFormat myFormat = new DecimalFormat(FORMAT_STRING);
myFormat.setGroupingSize(3);
myFormat.setGroupingUsed(true);

System.out.println(myFormat.format(10000000000000L));
}
}

这将输出:10,000,000,000,000

编辑,或者如果您必须使用 double ,您可以随时使用 System.out.printf(...)它使用 java.util.Formatter 的格式化功能。您可以在此处指定数字输出的宽度、要包含的小数位数以及是否包含组分隔符(使用 , 标志)。例如:

public static void main(String args[]) {
double planets = 840000;
double numofsun = 2.5;
double total = 0;
System.out.println("Galaxy #" + "\t" + "Planets");
for (int i = 1; i < 12; i++) {
double siSky = planets * numofsun;
total += siSky;
System.out.printf("%02d: %,14.2f%n", i, total);
}
}

返回结果:

使用 printf 的关键是使用正确的格式说明符。

  • %02d表示从 int 值创建一个数字字符串,宽度为 2 个字符,如果需要,前导 0。
  • %,14.2f表示从 float (由 f 指示)创建一个数字字符串,即 14 个字符宽,有 2 个小数位(由 .2 指示),并按 , 指示对输出进行分组。旗帜。
  • %n表示打印新行,相当于\n用于 print 或 println 语句。
<小时/>

编辑
或者更好的是,对列标题字符串和数据行字符串使用类似的格式说明符:

public class Stargazing {
public static void main(String args[]) {
double planets = 840000;
double numofsun = 2.5;
double total = 0;
System.out.printf("%8s %13s%n", "Galaxy #", "Planets");
for (int i = 1; i < 12; i++) {
double siSky = planets * numofsun;
total += siSky;
System.out.printf("%-8s %,13.2f%n", i + ":", total);
}
}
}

这将打印出:

Galaxy #       Planets
1: 2,100,000.00
2: 4,200,000.00
3: 6,300,000.00
4: 8,400,000.00
5: 10,500,000.00
6: 12,600,000.00
7: 14,700,000.00
8: 16,800,000.00
9: 18,900,000.00
10: 21,000,000.00
11: 23,100,000.00

关于java - 行星超出了数字框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824762/

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