3 回答

TA貢獻2037條經(jīng)驗 獲得超6個贊
您可以通過做一些數(shù)學運算、幾個基本循環(huán)以及使用printvs來避免計算邏輯println。首先,我將定義此處使用的變量:
//constants
int DIGITS_PER_LINE = 10; //your number of digits per line
int DIGITS_OFFSET = 2; //always 2, because 0 = '3' and 1 = '.'
String pi = /* your PI string */;
//input
int decimals = 42; //for example, from the user
然后,使用循環(huán)打印結(jié)果:
//We can calculate the number of lines we need from the start
int lines = decimals / DIGITS_PER_LINE; //4, to start
lines += (decimals % DIGITS_PER_LINE > 0) ? 1 : 0; //5, add a line for remainders
System.out.print("3");
System.out.println(decimals > 0 ? "." : "");
for (int line = 0; line < lines; line++) {
int offset = line * DIGITS_PER_LINE; //line -> result, 0 -> 0, 1 -> 10, 2 -> 20, etc
int digitsLeft = decimals - offset; //0 -> 42, 1 -> 32, ... , 4 -> 2
int toPrint = digitsLeft % DIGITS_PER_LINE; //up to the requested digit amount
for (int i = 0; i < toPrint; i++) {
System.out.print(pi.charAt(offset + i));
}
System.out.println();
}
請記住,代碼中的整數(shù)算術(shù)不會舍入;49/10is 4, and 49%10is 9(?;蛴鄶?shù)運算符)。
該語法boolean ? "something" : "another"稱為三元語句,如果它們令人困惑,我可以在沒有它們的情況下重寫它。您需要處理用戶輸入等,但永遠不要害怕解決問題。從一個可以以可變形式打印輸入的 x 個數(shù)字的程序開始,然后處理輸入。您可以將類似的內(nèi)容放入方法中printDigitsPI(int decimals)。上面使用的大多數(shù)變量都是常量,它們不會改變,也不需要傳遞。
作為最后一條建議,如果您發(fā)現(xiàn)自己將num1, num2, num3... 寫為變量,那么很可能有更好的方法來解決它。

TA貢獻1946條經(jīng)驗 獲得超4個贊
下面使用 Math.PI 創(chuàng)建 Double PI 的字符串表示形式。然后,我們使用 String#indexOf 確定該字符串中小數(shù)點的位置。然后,我們使用 Scanner 請求我們希望看到的小數(shù)位數(shù)。假設(shè)輸入是一個非負整數(shù),我們嘗試使用初始索引“.”查找字符串 PI 的子字符串。以及剩余的數(shù)字。
public static void main(String[] args) {
requestInput();
}
private static void requestInput() {
String pi = Double.toString(Math.PI);
int decimalOffset = pi.indexOf(".") + 1;
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the number of decimals of PI you would like to see: ");
int decimals = scanner.nextInt();
if (decimals < 0 || decimals > pi.length() + decimalOffset) {
requestInput();
return;
}
String result = pi.substring(0, decimals + decimalOffset);
System.out.println(String.format("The result of PI with %s numbers is %s", decimals, result));
}
}
添加回答
舉報