[英]How can i change these for statements to nested while statements?
我正在嘗試將嵌套的for循環更改為嵌套的while循環。 我嘗試了幾種不同的方法,但是每次嘗試都無法獲得預期的結果,即:T = 1 T = 1 T = 2 T = 4 T = 5 T = 11 R = 30
public static void main(String[] args) { int s = 0; int t = 1; //first for-loop i'm trying to make a while-loop for (int i = 0; i < 5; i++) { s = s + i; //second for-loop i'm trying to make a while-loop for (int j = i; j > 0; j--) { t = t + (j-1); } s = s + t; System.out.println("T is " + t); } System.out.println("S is " + s); }
嘗試這個:
public static void main(String[] args)
{
int s = 0;
int t = 1;
int i=0;
//first for-loop i'm trying to make a while-loop
while(i<5)
{
s = s + i;
int j=i;
//second for-loop i'm trying to make a while-loop
while(j>0)
{
t = t + (j-1);
j--;
}
s = s + t;
System.out.println("T is " + t);
i++;
}
System.out.println("S is " + s);
}
請參閱下面的內聯評論:
int s = 0;
int t = 1;
int i = 0; // init i outside the while-loop
while (i < 5) // replaces for-loop stop condition
{
s = s + i;
int j = i; // init j outside the while-loop
while (j > 0) // replaces for-loop stop condition
{
t = t + (j-1);
j--; // decrement j
}
s = s + t;
System.out.println("T is " + t);
i++; // increment i
}
System.out.println("S is " + s);
輸出
T is 1
T is 1
T is 2
T is 5
T is 11
S is 30
一般來說,轉
for (int i = 0; i < 5; i++) {
// stuff goes here
}
進入while循環,您將初始化移到它的前面,將條件放入while作為條件,最后將增量(或其他更改步驟)放入循環內。
int i = 0;
while (i < 5) {
// stuff goes here
i++;
}
同樣的邏輯也應適用於您的內部循環。
所有初始化語句都放在while循環的開始塊之前,而所有增量/更新語句都在循環將其結束塊放置的底部執行! 所以,只需在循環體之前移動初始化並在退出循環之前推送增量/減量操作...
轉換后的答案將是:
int i=0;
while(i<5)
{
s = s + i;
//second for-loop i'm trying to make a while-loop
int j=i;
while(j>0)
{
t = t + (j-1);
j--;
}
s = s + t;
System.out.println("T is " + t);
i++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.