承接上一節,本節,我從具體實例出發,講解下while、do-while以及for3種循環語句的運用。
範例:
問題:假設某個大學今年的學費是20000美金,而且以每年9%的速度增加,多少年之後學費會翻倍?
分析:根據問題情境,第二年的學費是第一年的學費乘以1.09。以此類推,以後每年的學費都是上一年的學費乘以1.09。於是,每年的學費可以如下表示:
double t=20000;int y=1;
t= t*1.09;y++;
t= t*1.09;y++;
t= t*1.09;y++;
…
不斷地計算新年度的學費,直到學費至少是40000美金為止。可以將此種算法設計成以下的while循環:
double t=20000;
int y= 1;
while(t<40000){
t= t*1.09;
y++;
}
完整的程序用while循環表示如下:
public class Future {
public static void main(String[] args) {
double t=20000;
int y= 1;
while(t<40000){
t= t*1.09;
y++;
}
System.out.println(“T will be doubled in ”+y+“ years”);
}
}
這個程序用do-while循環表示,則如下:
public class Future {
public static void main(String[] args) {
double t=20000;
int y= 0;
do{
t= t*1.09;
y++;
} while(t<40000)
System.out.println(“T will be doubled in ”+(y+1)+“ years”);
}
}
這個程序用for循環表示,則如下:
public class Future {
public static void main(String[] args) {
double t=20000;
int y;
for(y=1;t<40000;y++){
t= t*1.09;
}
System.out.println(“T will be doubled in ”+y+“ years”);
}
}
通過這個例子,請大家好好體會體會3種循環語句的異同之處!好了,本節到此結束!
閱讀更多 計算機編程的全部事兒 的文章