我在生成随机数时遇到问题。我不知道我怎么能写它以及为什么当我添加if语句时它不起作用。谢谢你的帮助。
static void Main(string[] args)
{
int first= 1;
int second = 2;
{
Random r_first = new System Random();
r_first = r_first.next(-100, 0);
Console.WriteLine(first); // I would like to see the result
Random r_second = new System Random();
second = r_second.next(-100, 0);
Console.WriteLine(second); // I would like to see the result
if (first > second)
{
Console.WriteLine("first is bigger");
}
else
{
Console.WriteLine("first is smaller");
}
}
}
}
答案 0 :(得分:2)
您的代码中有多个错误。
Random
实例。大多数时候它会给出相同的价值。所以你需要一个Random
类的实例。Next
而不是next
撰写System.Random()
,而不是System Random()
static void Main(string[] args)
{
int first = 1;
int second = 2;
{
Random randomIns = new System.Random();
first = randomIns.Next(-100, 0);
Console.WriteLine(first); // I would like to see the result
second = randomIns.Next(-100, 0);
Console.WriteLine(second); // I would like to see the result
if (first > second)
{
Console.WriteLine("first is bigger");
}
else
{
Console.WriteLine("first is smaller");
}
}
}
答案 1 :(得分:0)
问题1:您正在将随机整数值分配给Random
类引用变量r_first
。
替换它:
r_first = r_first.next(-100, 0);
有了这个:
first = r_first.Next(-100, 0);
问题2:
如果不是拼写错误,您应该使用System.Random();
而不是System Random();
答案 2 :(得分:0)
1)您不必多次拨打新的随机信息。
2)你不能为随机方法赋值(rng = rng.Next() - 你不能这样做,你必须定义新变量来保存rng方法的结果)
3)Random是System命名空间的一部分,所以只调用Random()
的System.Random()试试这个:
static void Main(string[] args)
{
int first = 1;
int second = 2;
Random rng = new Random();
first = rng.Next(-100, 0);
Console.WriteLine(first); // I would like to see the result
second = rng.Next(-100, 0);
Console.WriteLine(second); // I would like to see the result
if (first > second)
{
Console.WriteLine("first is bigger");
}
else
{
Console.WriteLine("first is smaller");
}
}