我試圖編寫一個程序,通過重複整數除法來模擬對數。用戶輸入他們想要記錄的基本號和值X.代碼運行一個循環,並在每次連續的分割後遞增計數。代碼被設置爲在X的值比base小,因爲我只使用int類型變量而停止。通過重複整數除法模擬對數
此代碼適用於某些數字和基數,但對於其他數字則會給出錯誤的值。它「log_2(64)爲6」,然而它不這樣做的100 log_10它給出了10
public static void main(String[] args) {
Scanner inScan = new Scanner(System.in);
int base;
int X;
int response;
int n=0;
do{
System.out.println("Java Lab 3 Logarithm Solver.");
System.out.println("Please enter a base > 1");
base = inScan.nextInt();
System.out.println("Please enter a number, X>0.");
X = inScan.nextInt();
if (X > 0 && base > 1){
System.out.println("Logarithm base " +base+ " of " +X+" is ");
for (; X>base ;n++){
X=(X/base);
}
System.out.println(n);
} else {
System.out.println("Invalide numbers.");
}
System.out.println("Would you like to go again? Press 1, press 0 to quit");
response = inScan.nextInt();
} while (response == 1);
}
}
你試過用調試器(如IDE提供的調試器)遍歷代碼? – hexafraction 2014-09-13 16:04:14
檢查'n'被重置爲零的位置。順便說一句,乘以底部比底部劃分要快。 – 2014-09-13 16:06:21
hexafraction-是的,它似乎沒有幫助。 拉撒路 - 我試着乘坐基地,它似乎工作正常。我只需要修復for循環的邏輯。謝謝。 – 2014-09-13 16:56:05