我無法弄清楚如何根據它們相應的(輸出右側的數字)計數顯示一個舍入數量的星號。Java:循環遍歷和基於四捨五入的打印
我試圖用1個星號來表示100個星號。但是,當我得到一個數字,例如第17卷是417時,我希望它只打印4個星號,而不是5個;相同的四捨五入。我嘗試使用Math.round(),但我沒有成功。
我非常感謝任何幫助。
我的代碼:
public class Histogram {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numRoles = 30000;
int[] amountRoles = new int[19]; // amountRoles Holds the Array
for (int i = 3; i < 7; i++)
amountRoles[i] = 0; // Set 0
{
for (int i = 0; i < numRoles; i++)
{
int die1 = (int)(Math.random()*6+1);
int die2 = (int)(Math.random()*6+1);
int die3 = (int)(Math.random()*6+1);
amountRoles[die1+die2+die3]++; // Increments
}
System.out.print("The die was rolled " + numRoles + " times, its six value's counts are:");
for (int i = 3; i < 7; i++)
{
System.out.println(); // Line Holder
}
}
for (int i = 3; i < amountRoles.length; i++) // Iterates through amountRoles
{
System.out.print("[" + i + "]" + " ");
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
if (Math.round(j) % 100 == 0)
{
System.out.print("" + "*");
}
}
System.out.println(" " + amountRoles[i]);
}
}
}
我的輸出:
[3] ** 139
[4] **** 389
[5] ********* 826
[6] ************** 1366
[7] ********************* 2082
[8] ****************************** 2973
[9] *********************************** 3440
[10] *************************************** 3859
[11] ************************************** 3742
[12] *********************************** 3482
[13] ****************************** 2918
[14] ******************** 1996
[15] ************** 1341
[16] ********* 865
[17] ***** 417
[18] ** 165
你在那裏有什麼不處理向上舍入,只是四捨五入。因此,當8是希望時,773會打印7個星號。示例自773> 750以來,圍繞並打印8個星號(742 <750),向下捨去並打印7個星號。 – Aramza
@Aramza啊我明白了。沒問題,這很容易解決。讓我編輯答案。 – nhouser9