该问题要求1000次迭代代码。它必须允许0-100000的整数,并显示在迭代期间生成了多少个奇数,然后显示生成的最大数字和最小数字。我的代码的第一部分工作并显示生成了多少个奇数但是我无法弄清楚如何捕获/编辑代码运行时生成的最小和最大数字。
我尝试过很多不同的方法,包括while循环和if if,else if条件。我把它们放在我的程序中但是我被卡住了。我知道问题在于randNum进入变量并在每次迭代中保持不变而不回零。(当我运行我的代码时,它显示为smallNum和LargeNum为零。)
到目前为止,这是我的工作
using System;
using System.Windows.Forms;
namespace BissonnetteMessageBox
{
class Program
{
static void Main(string[] args)
{
int oddNumCount = 0;
int smallNum = 0;
int largeNum = 0;
Random randNum = new Random();
for (int i = 0; i < 1000; i++)
{
int num = randNum.Next(100000);
int remain = num % 2;
if (remain != 0)
{
oddNumCount++;
}
if (num < smallNum)
{
num = smallNum;
}
else if (num > largeNum)
{
num = largeNum;
}
}
MessageBox.Show("the Number of odd numbers generated: " + oddNumCount +
"\nSmallest number was: " + smallNum +
"\nLargerst number was: "+ largeNum , "random number generation results");
}
}
}
这是我运行程序时的结果:
行“num = smallNum;”和“num = largeNum;”错了。它们应该是“smallNum = num;”和“largeNum = num;”。那是因为“=”右侧的变量(或常量,表达式)会覆盖左侧的变量。它不像数学,它可以转身。这是正确的代码:
using System;
using System.Windows.Forms;
namespace BissonnetteMessageBox
{
internal class Program
{
private static void Main(string[] args)
{
int oddNumCount = 0;
int smallNum = 0;
int largeNum = 0;
Random randNum = new Random();
for (int i = 0; i < 1000; i++)
{
int num = randNum.Next(100000);
int remain = num % 2;
if (remain != 0)
{
oddNumCount++;
}
if (num < smallNum)
{
smallNum = num;
}
else if (num > largeNum)
{
largeNum = num;
}
}
MessageBox.Show("the Number of odd numbers generated: " + oddNumCount +
"\nSmallest number was: " + smallNum +
"\nLargerst number was: " + largeNum, "random number generation results");
}
}
}
许多人已经指出了代码本身的两个主要问题。
我想谈谈在学习如何编程时如何处理这样的问题。
看起来你在Visual Studio中,用C#编程。嗯,好消息是,当你逐步完成你的程序时,Visual Studio让你很容易看到正在发生的事情。您可以在代码中设置断点,以便当程序到达该行时,它会停止 - 突出显示该行并让您看到正在发生的事情。从那里,您可以前进代码行,观察值的变化。
以下是一些有用的入门地点:
这将是非常有价值的未来。因为,说实话,如果你发现自己不得不在网上发布任何问题,那么你就不会非常喜欢编程。能够找出障碍会让你的生活更加愉快:-)