C#如何找到随机数数组中最低数的出现次数

  • 本文关键字:何找 随机数 数组 c#
  • 更新时间 :
  • 英文 :


我试图用随机生成的数字显示数组中最低数字的出现次数。最低的数字是在数组的末尾确定的(在我的程序中(

using System;
using System.Threading;
namespace Assignment2
{
class Program
{
static void Main(string[] args)
{
int[] n = new int[20]; // make new array of 20 elements
int i;
int min = 151;
int count = 0;
Random random = new Random();
for (i = 0; i < 20; i++)
{
n[i] = random.Next(0, 150); // give n[i] 20 random numbers //
if (n[i] < min) // Find the lowest number in random generated array
{
min = n[i];
}
Console.WriteLine("Element {0} = {1}", i, n[i]); // show the elements and it's values
if (n[i] == min) // number of occurence perhaps?
{
count++;
}

if (i == 19) // Print smallest number/number of occurence
{
Console.WriteLine();
Console.WriteLine("Smallest number = {0}", min);
Console.WriteLine("Number of occurence = {0}", count);
}
}
Console.ReadKey();
}
}
}

虽然您的问题不清楚,但计数不正确的原因是count变量在找到新的较低数字时不会重置。要修复此问题,只需在设置新的min变量时添加count = 0;,如:

if (n[i] < min) // Find the lowest number in random generated array
{
min = n[i];
count = 0; // reset count
}

最新更新