【发布时间】:2015-03-07 23:29:59
【问题描述】:
有一个作业,“编写一个程序,生成 0 到 100000 之间的 1000 个随机数。显示生成的奇数值的数量以及最小值和最大值。”
编写代码,如果其中一个随机数出现奇数/最大/
所有这些都写好了,但我似乎找不到让我的 max/min/odd 语句起作用的正确位置。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RandomNumberFacts
{
class RandomNumberFacts
{
static void Main()
{
bool moreData = true;
Random numb = new Random();
int s = numb.Next(100000);
int max = -1;
int min = 100001;
int odd = 0;
int counter = 0;
while (moreData)
{
counter++;
if (counter >= 1000)
{
moreData = false;
}
else
{
s = numb.Next(100000);
}
if (s < min)
s = min;
if (s > max)
s = max;
if (s % 2 == 1)
odd++;
}
Console.WriteLine("Amount of odd numbers in set is:");
Console.WriteLine(odd);
Console.WriteLine("Largest number in set is:");
Console.WriteLine(max);
Console.WriteLine("Smallest number in set is:");
Console.WriteLine(min);
Console.ReadKey();
}
}
}
【问题讨论】:
-
您在测试了最小值/最大值后反转了赋值。你需要
min = s和max = s -
不是 s = max,而是 max =s
-
用 for 循环代替 while 循环会更容易阅读。
-
另外,s 没有在循环的最后一次迭代中设置
-
@Measuring: “介于 0 和 100000 之间”因此不清楚 100000 是否是有效结果。就此而言,尚不清楚 0 是否为有效结果。
标签: c#