我在这里撞墙,我的同胞们。有没有办法可以生成随机数,然后指出它们是正面还是负面?
我尝试使用if
语句,但正如您所知,一旦它到达if
,它就不会转到else
。
请保持您的代码简单,以便任何人都能理解正在发生的事情,或至少说明您的代码中发生了什么。
我该如何解决这个错误?
Random rnd = new Random();
Console.WriteLine("\n5 random integers from -100 to 100:");
for (int X = 1; X <= 5; X++)
{
if (X >= 0)
{
Console.WriteLine("These are the positive numbers: {0}", rnd.Next(0, 100));
}
else
{
Console.WriteLine("These are the negative numbers: {0}", rnd.Next(-100, 0));
}
}
Console.ReadLine();
答案 0 :(得分:1)
您正在检查x
的值。它将始终保持积极态度。在你的循环中试试这个:
int i = rnd.Next(-100, 100);
if (i >= 0)
//It is positive
else
//It is negative
答案 1 :(得分:1)
尝试以下代码......不要比较X;你必须比较随机数。
Random rnd = new Random();
Console.WriteLine("\n5 random integers from -100 to 100:");
for (int X = 1; X <= 5; X++)
{
int y = rnd.Next(-100, 100);
if (y >= 0)
{
Console.WriteLine("These are the positive numbers: {0}", y.ToString());
}
else
{
Console.WriteLine("These are the negative numbers: {0}", y.ToString());
}
}
Console.ReadLine();
答案 2 :(得分:0)
这将完成工作:
Random rnd = new Random();
int randomNumber = rnd.Next(-100, 100);
if (randomNumber >= 0)
Console.WriteLine("Positive (with Zero)");
else
Console.WriteLine("Negative");
答案 3 :(得分:0)
我认为这将完全符合您的要求:
public static void Main(string[] args)
{
var rnd = new Random();
Console.WriteLine("\n5 random integers from -100 to 100:");
List<int> random = new List<int>();
for (int X = 1; X <= 5; X++)
{
random.Add(rnd.Next(-100, 100));
}
Console.WriteLine("These are the positive numbers:");
foreach (int number in random)
{
if (number >= 0)
{
Console.WriteLine(number);
}
}
Console.WriteLine("These are the negative numbers:");
foreach (int number in random)
{
if (number < 0)
{
Console.WriteLine(number);
}
}
Console.ReadLine();
}
这将打印出5个数字,并将它们显示在如下所示的结果集中:
答案 4 :(得分:0)
Random rnd = new Random();
Console.WriteLine("\n5 random integers from -100 to 100:");
for (int X = 1; X <= 5; X++)
{
int Y = rnd.Next(-100, 100);
if (Y > 0)
{
Console.WriteLine("These are the positive numbers: {0}", Y);
}
else
{
Console.WriteLine("These are the negative numbers: {0}", Y);
}
}
答案 5 :(得分:0)
使用continue
是另一种方式:
Random rnd = new Random();
Console.WriteLine("\n5 random integers from -100 to 100:");
for (int X = 1; X <= 5; X++)
{
int y = rnd.Next(-100, 100);
if (y < 0)
{
Console.WriteLine("These are the negative numbers: {0}", y);
continue;
}
Console.WriteLine("These are the positive numbers: {0}", y);
}
Console.ReadLine();