Domanda

I have the following code:

decimal xtop = 2.0m, xbot = -2.0m, ytop = 2.0m, ybot = -2.0m, checkx, checky;
string inputx, inputy; 
while (true)
{
    Console.WriteLine("Input number x:");
    inputx = Console.ReadLine();
    if (decimal.TryParse(inputx, out xtop))
    {
        checkx = decimal.Parse(inputx);
        Console.WriteLine("Input number y:");
        inputy = Console.ReadLine();

        if (decimal.TryParse(inputy, out xtop))
        {
            checky = decimal.Parse(inputy);
            checky = 0.5m;
            if (checkx >= xbot && checkx <= xtop && checky >= ybot && checky <= ytop)
            {
                Console.WriteLine("The input is inside the rectangle");
            }
            else
            {
                Console.WriteLine("The input is outside the rectangle");
            }
            break;
        }

    }
}

If the inputs from the console are: x = 1 and y = 0,5 I get the following bug. As you can see, both numbers are in the limits needed to print the true value. However, I get the false value anyway. This happens if the values are in double as well. Can someone explain why does this happen ?

È stato utile?

Soluzione

You are reassigning the value of xtop twice when you use it as the out argument for TryParse. The second time you put it as the out argument is where it becomes 0.5 and so checkx <= xtop becomes false.

if (decimal.TryParse(inputy, out xtop))

When you use out it means that you are going to assign that value.

Altri suggerimenti

I dont know if you use commas where I use decimal points, but isnt checky supposed to be set to 0.5 and not 0,5? On my compiler if I set checky = 0.5 the program prints The input is in the circle. Which is reasonable apart from the fact that it's a test for being inside a square.

Apply the correct culture when parsing the number:

var myCulture = new CultureInfo("de-DE"); // Adapt to your culture;
if (Decimal.TryParse(inputx, NumberStyles.Float, myCulture, out checkx)) {
    ...
}

And you are also parsing four times. Review your logic!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top