2016-05-13 173 views
0

我很想知道如何將以下代碼轉換爲while循環。我知道在這種情況下它並沒有什麼意義,但我正在學習一本學生手冊,並希望看到另一個例子。在此先感謝,任何幫助非常感謝。將循環轉換爲while循環c#

int sides = 0; 
int number = 0; 
int total = 0; 

Random random = new Random(); 
Console.WriteLine("Choose the number of sides."); 
sides = int.Parse(Console.ReadLine()); 
Console.WriteLine("Choose number of dice."); 
number = int.Parse(Console.ReadLine()); 

for (int i = 0; i < number; i++) 
{ 
    int die = random.Next(1, sides); 
    Console.WriteLine("You Rolled {0}", die.ToString());d 
    total += die; 
} 

Console.WriteLine("Your total is {0}", total); 
Console.ReadLine(); 

回答

4
int i = 0; 
while(i < number) 
{ 
     int die = random.Next(1, sides); 
     Console.WriteLine("You Rolled {0}", die.ToString()); 
     total += die; 
     i++ 
} 
+2

這很快。當我的答案出現時,我在'while'中鍵入「w」 – Zuzlx

0

你想一個for-loop轉換爲while-loop,如果我理解正確。

int currentNum = 0; 
while (currentNum < number) 
{ 
    int die = random.Next(1, sides); 
    Console.WriteLine("You Rolled {0}", die.ToString()); 
    total += die; 

    currentNum++; 
} 
+0

代碼中有錯誤。在第五行的末尾只有一個「d」。 – Spilarix

+0

@Spilarix好抓。除去。 – Rhs