[英]Generating random numbers 1-100
I need to generate random numbers from 1 to 100 and I know how to do that part... 我需要生成从1到100的随机数,我知道如何做这个部分......
I need to ask user how many numbers he wants to generate(if he says 5 the program needs to generate 5 numbers from 1 to 100). 我需要问用户他要生成多少个数字(如果他说5,则程序需要从1到100生成5个数字)。 I only now how to make a fixable amount by adding new int's in a list. 我现在只知道如何通过在列表中添加新的int来创建可修复的金额。
I did achieve that before, but then i couldn't make it work, so it would write average of those numbers and min+max value. 我以前确实做到了,但是后来我做不到,因此它将写出这些数字的平均值和min + max值。
Here is my code below: 这是我的代码如下:
Random k = new Random();
//here i added in the same way other variables and put them in a list
int j = k.Next(100);
Console.WriteLine("");
double[] list1 = {j};
double povp = list1.Average();
Console.WriteLine(povp);
Console.WriteLine("");
Console.WriteLine(list1.Max());
Console.WriteLine("");
Console.WriteLine(list1.Min());
Console.ReadKey();
您可以使用以下代码生成N个数字:
IEnumerable<int> numbers = Enumerable.Repeat(1,N).Select(_ => random.Next(100));
// ask user for input
string input = Console.Readline();
int parsed;
// parse to int, needs error checking (will throw exception when input is not a valid int)
int.TryParse(input, out parsed);
Random random = new Random();
List<double> list = new List<double>();
for(int i = 0; i < parsed; parsed++)
{
list.Add(random.Next(100));
}
public void Main()
{
const int NUMBERS_FROM = 1;
const int NUMBERS_TO = 100;
int n = int.Parse(Console.ReadLine());
Random rnd = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i < n; i++)
{
int rndNumber = rnd.Next(NUMBERS_FROM, NUMBERS_TO + 1);
numbers.Add(rndNumber);
}
Console.WriteLine("Numbers : {0}",string.Join(", ",numbers));
}
this will generate N numbers and add them to a list and then print them to the console. 这将生成N个数字并将它们添加到列表中,然后将它们打印到控制台。 I think this is what you were looking for 我想这就是你要找的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.