This piece of code was written to generates 100 random numbers between 0 and 1000 and display the number of even values generated as well as the smallest, the largest, and the range of values.
When I compile I’m getting an error about using unassigned local varibale of minInt and maxInt. It is supposed to get assigned variable from the generator, what did I do wrong?
using System;
using System.Windows.Forms;
namespace ConsoleApplication27
{
class Program
{
static void Main(string[] args)
{
int evenNumbers = 0;
int minInt;
int maxInt;
int range;
string result;
range = maxInt - minInt;
result = "Even numbers:\t" + evenNumbers;
result += "\nMin number:\t" + minInt;
result += "\nMax number:\t" + maxInt;
result += "\nRange of number:\t" + maxInt + " - " + minInt + " = " + range;
DisplayResults(result);
}
static void GenerateNumbers(int evenNumbers, int minInt, int maxInt, int range)
{
//creating 100 element array
//and using the random function to fill it
int[] randomNumbers = new int[100];
Random number = new Random();
int randy;
for (int i = 0; i < randomNumbers.Length; i++)
{
randy = number.Next(1000);
randomNumbers[i] = randy;
if (randy < minInt)
{
minInt = randy;
}
else
if (randy > maxInt)
{
maxInt = randy;
}
if (randomNumbers[i] % 2 == 0)
{
evenNumbers++;
}
}
}
static void DisplayResults(string outcome)
{
MessageBox.Show(
outcome, "results!",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
I suspect your main problem is you never assign the random number to
randy:EDIT: I’m surprised this even compiles. Shouldn’t it have complained about attempting to use an non-initialized variable?
EDIT: In addition, you need to assign some value to
minIntandmaxIntin yourMainmethod. After these fixes, it should compile (but won’t give you the result you need as you do not invokeGenerateNumbersor gather the results out of it. For that you should useref:Then your
GenerateNumbersmethod:(I took out the
rangeparameter as it wasn’t used)Also note that I set your
minIntandmaxIntvariables to the maximum/minimum values initially. This means that they’ll they’ll take the first random value, then subsequently keep it updated.EDIT: Cleaned the generator code a bit too. Watch out for the
if < elseif >check as there are corner case conditions where if there are too few random numbers and too small a range, or each of the random numbers generated are descending, it’s plausible that your “else if (randomNumber > maxInt” check will never execute.