将for循环转换为while循环c#

时间:2016-05-13 21:36:41

标签: c# loops for-loop while-loop

我很想知道如何将以下内容转换为while循环。我知道在这种情况下它没有最有意义,但我正在研究学生工作簿,并希望看到另一个例子。在此先感谢,非常感谢任何帮助。

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();

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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++;
}