我做了一个简单的程序,用户决定程序中将使用多少个数字。
程序然后随机生成数字量。如何一起计算这些随机数?
<div class="album text-muted">
<div class="container">
<div class="row">
<% @products.each do |product| %>
<div class="card">
<%= image_tag("picture_holder")%>
<strong class="card-text"><%= product.summary %></strong>
<a href="<%= product_path(product) %>"><%= image_tag("picture_holder")%><a>
<p class="card-text"><%= product.price %></p>
<p class="card-text"><%= product.description %></p>
</div>
<% end %>
</div>
<div class="row">
<div class="col-md-12">
<%= paginate @products %>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
你必须在while循环中求和,而不是在外面:
while (counter < amountOfNumbers) {
counter++;
int randomNumber = generateRandNums.Next(20);
calcRandomNumbers += randomNumber;
Console.Write(randomNumber + ", ");
}
您还可以将所有数字存储在List<int>
中,然后使用list.Sum()
。
答案 1 :(得分:0)
var list = new List<int>();
for (int i = 0; i < amountOfNumbers; i++)
list.Add(generateRandNums.Next(20));
calcRandomNumbers = list.Sum();
答案 2 :(得分:0)
这看起来你错过了一些代码安排让我很困惑为什么你使用 calcRandomNumbers = + randomNumbers; out of while子句如果你想要总和。
class Program
{
static void Main(string[] args)
{
int amountOfNumbers;
int counter = 0;
int randomNumbers = 0;
int calcRandomNumbers=0;
Random generateRandNums = new Random();
Console.WriteLine(generateRandNums.Next(5, 29));
Console.WriteLine("\nHow many numbers do you want to be entered?");
amountOfNumbers = Convert.ToInt32(Console.ReadLine());
while (counter < amountOfNumbers)
{
counter++;
randomNumbers = generateRandNums.Next(20);
Console.Write(randomNumbers + ", ");
calcRandomNumbers = +randomNumbers;
}
Console.WriteLine("The final sum is " + calcRandomNumbers);
Console.ReadKey();
}
}