2015-10-14 89 views
0

我在這裏是新來的,並試圖獲得有關學校工作的幫助。我需要這樣的代碼:在C++的重複結構中用while語句替換for語句

do //begin loop 
{ 
    cout << "Year " << years << ":" << endl; 

    for (double rate = .02; rate < .05; rate += .01) 
    { 
      balance = principal * pow(1 + rate, years); 
      //Display rate with zero decimal places 
      cout << fixed << set precision(0); 
      cout << " Rate " << rate * 100 << "%: $"; 
      //Display balance with two decimal places 
      cout << setprecision(2) << balance << endl; 
    } //End for 

    //Update years counter 
    years += 1; 
} while (years < 6); 

從一個for語句轉到while語句。我遇到了一些問題,希望能夠對如何正確執行此操作有所瞭解。謝謝!

+0

什麼特別的問題?你嘗試了什麼? –

+1

你能解釋/顯示你試過的例子嗎?請閱讀此處,瞭解如何提出作業問題以及應該包括哪些內容以確保您能夠得到答案,而不僅僅是低調和忽略:) http://meta.stackexchange.com/questions/10811/how-do-i -ask-and-answer-homework-questions – Sk93

+0

你知道'for'語句有3個部分嗎?你有沒有發現他們? while語句只有一個表達式,你應該知道'for'循環的三個部分中的哪一個對應於這個表達式。 – MSalters

回答

0

你首先需要了解什麼for循環的作用:

double rate = 0.2 // initialization 
rate < .05 // condition and 
rate += .01 // the afterthought. 

所以剛開始你設置你的速度變一次,然後要檢查,如果速度你ingrement下一循環之前小於0.05和率.01。

你可以做同樣的事情與while循環,如果你在循環之前添加:

double rate = 0.2 

,並在循環的末尾添加:

rate += .01