我正在瀏覽一個用於計算投資的代碼,直到它已經翻了一番,我收到了一個我無法解決的無限循環。誰能弄清楚爲什麼這給了我一個無限循環?我經歷過自己,但似乎無法找到問題所在。所提到的「時期」是每年有多少次利息被複合。爲什麼這給了我一個無限循環?
double account = 0; //declares the variables to be used
double base = 0;
double interest = 0;
double rate = 0;
double result = 0;
double times = 0;
int years = 0;
int j;
System.out.println("This is a program that calculates interest.");
Scanner kbReader = new Scanner(System.in); //enters in all data
System.out.print("Enter account balance: ");
account = kbReader.nextDouble();
System.out.print("Enter interest rate (as decimal): ");
rate = kbReader.nextDouble();
System.out.println(" " + "Years to double" + " " + "Ending balance");
base = account;
result = account;
for (j=0; j<3; j++){
System.out.print("Enter period: ");
times = kbReader.nextDouble();
while (account < base*2){
interest = account * rate/times;
account = interest + base;
years++;
}
account = (((int)(account * 100))/100.0);
//results
System.out.print(" " + i + " " + account + "\n");
account = result;
}
的代碼應該問三個「時期」,或三個不同的時間輸入的數據爲每年(前每年,每月,每天等)複合
非常感謝!
你嘗試過調試這一點,在代碼中設置斷點,單步運行它? – Bohemian
不,我在使用IDE時比較新,BlueJ。你有什麼建議嗎? – ParaChase
不能保證對'int'的轉換不會導致'account'降到base的值以下。如果'base * 2> = Integer.MAX_INTEGER'。另外,由於'times'爲0,我相信'(int)'強制轉換總是會將'Integer.MAX_INTEGER'留在'account'中。 –