[英](JAVA) Print a table displaying numbers from 1-10 that print the number, its cube root, square root, square root, square, and cube
打印一張從 1 到 10 的數字表格,以表格形式顯示數字、其立方根、平方根、平方和立方。
這是所需的 output:
我的代碼:
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= 5; j++)
System.out.printf("%6d", i, Math.cbrt(i) + " " + Math.sqrt(i) + " " + (i * i) + " " + (i * i * i));
System.out.println();
}
}
}
我的代碼給出了 output:
0 0 0 0 0 0
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7
8 8 8 8 8 8
9 9 9 9 9 9
10 10 10 10 10 10
誰能幫我找到正確的 output?
您必須使用不同的格式說明符來打印浮點和整數。
此外,在System.out.printf()
中,您可以使用逗號分隔值,
。 看到這個。
%d
- 整數
%f
- 浮點數
%.6f
- 用於 6 位精度的浮點數
另外,我刪除了額外的嵌套 for 循環,這是不必要的。
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
System.out.printf("%d %.6f %.6f %d %d\n", i, Math.cbrt(i), Math.sqrt(i), (i * i), (i * i * i));
}
}
由於這顯然是一個 class 分配,我只會給你一個提示。 您通常會創建一個長字符串以輸入 printf 方法並要求將其格式化為數字。
printf 方法也可以處理許多 arguments (vararg),因此可以逐行饋送許多 arguments 或分離成一個 ZAFA0FF8B27B876FDE76 計算。
https://www.baeldung.com/java-printstream-printf#2-float-and-double-formatting
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.