C#-添加两个带有随机数的整数变量

时间:2018-09-27 03:16:58

标签: c#

如何将2个整数的值相加并将其合并,并使用1-10之间的随机数继续计数到50。

目前int humanRandomScore = random.Next(MIN, MAX);刚刚为其重新分配了一个新的随机数。我该如何继续添加而不是重新分配值。

如果我尝试将随机数添加到humanGameScore变量中,则会产生错误

const int raceLength = 50;
int humanGameScore = 0;
Random random = new Random();

while (humanGameScore <= raceLength)
{
       int humanRandomScore = random.Next(MIN, MAX);
       int combinedNumbers = humanRandomScore + humanGameScore;

       Console.WriteLine(combinedNumbers);
       Console.ReadKey();
       Console.Clear();
}

2 个答案:

答案 0 :(得分:0)

将其声明移出循环:

const int raceLength = 50;
int humanGameScore = 0;
Random random = new Random();    
while (humanGameScore <= raceLength)
{
       humanGameScore += random.Next(MIN, MAX);               
       Console.WriteLine(humanGameScore);
       Console.ReadKey();
       Console.Clear();
}

答案 1 :(得分:0)

在我看来,这是您要的内容:

const int MIN = 1;
const int MAX = 10;

const int raceLength = 50;
int humanGameScore = 0;
Random random = new Random();

while (humanGameScore <= raceLength)
{
    humanGameScore += random.Next(MIN, MAX + 1);
}

Console.WriteLine(humanGameScore);
Console.ReadKey();
Console.Clear();