Home > Back-end >  Why is the code outputing a zero as the highest negative number?
Why is the code outputing a zero as the highest negative number?

Time:12-12

In the code I want to get the highest negative number but maxNegative never even gets set. Why is that?

int number;
int? maxNegative = null;
bool foundNegative = false;

do
{
    Console.Write("Enter a number: ");
    number = int.Parse(Console.ReadLine());

    if (number <= -1)
    {
        foundNegative = true;

        if ( number <= -1 && number > maxNegative)
        {
            maxNegative = number;
        }
    }
} while (number != 0);

if (foundNegative)
{
    Console.WriteLine("The maximum negative number is: "   maxNegative);
}
else
{
    Console.WriteLine("jh");
}

I tried making it < 0 and also <= -1. Also I tried and made it the lowest negative number and it worked fine.

CodePudding user response:

but maxNegative never even gets set

That's because you have this in your inner if statement

number > maxNegative

maxNegative is null. A number cannot be greater than null. Nor can a number be less than or equal to null. These will always evaluate to false.

This causes the inner if statement to never execute, thus maxNegative never gets changed from its initial null value.


Let's do some cleanup of the code.

You don't need the foundNegative variable. You already know if a negative was found based on maxNegative itself - if maxNegative is null you didn't find a negative. If maxNegative is not null you did find a negative.

Now, the if statements.

The outer if statement checks if the number is negative. That one's fine. The inner if statement we want to change around.

The first thing to do is if maxNegative is null, we should just blindly overwrite it with the input number. Because of the outer if statement we already know that number will be negative, and because maxNegative is null, this is the first negative we've found, so it's automatically the largest.

If, however, maxNegative is not null, then you should evaluate if number is larger or not.

These two cases can be combined in one if statement with an OR.

int? maxNegative = null;
int number;

do
{
    Console.Write("Enter a number: ");
    number = int.Parse(Console.ReadLine());

    if (number <= -1)
    {
        if (maxNegative is null || number > maxNegative)
        {
            maxNegative = number;
        }
    }
} while (number != 0);

if (maxNegative is not null)
{
    Console.WriteLine("The maximum negative number is: "   maxNegative);
}
else
{
    Console.WriteLine("No negative numbers inputted");
}
  •  Tags:  
  • c#
  • Related