简体   繁体   中英

Is it possible to return multiple values with multiple ifs? C#

    double GPoint = 0, GPer;
    string Des = null;
    
    Console.WriteLine("Enter your Equivalence Grade");
    GPer = double.Parse(Console.ReadLine());
    
    if (GPer >= 95 && GPer <= 100)
        GPoint = 1.00;
        Des = "Excellent";
    
    if (GPer >= 91 && GPer <= 94)
        GPoint = 1.25;
        Des = "Superior";
    
    if (GPer >= 88 && GPer <= 90)
        GPoint = 1.50;
        Des = "Very Good";
    
    if (GPer >= 86 && GPer <= 87)
        GPoint = 1.75;
        Des = "Good";
    
    if (GPer >= 84 && GPer <= 85)
        GPoint = 2.00;
        Des = "Very Satisfactory";
    
    Console.WriteLine( "Your final grade is {0}, a {1} Grade."
                      ,GPoint
                      ,Des);

It only does the first variable correctly but the second value always prints the last if statement. So it always returns "Very Satisfactory" on any value.

Firstly, in modern C# I'd probably do this with a switch expression and tuples (and I'd also change the local variable names to be more meaningful and idiomatically-cased)... but leaving that aside, the immediate problem is that your indentation suggests you think that this:

if (GPer >= 88 && GPer <= 90)
   GPoint = 1.50;
   Des = "Very Good";

... only assigns Des if the condition is met. That's not true. That code is equivalent to:

if (GPer >= 88 && GPer <= 90)
{
   GPoint = 1.50;
}
Des = "Very Good";

If your if statement body needs to contain multiple statements, you need to use a block body. Personally I would recommend always using a block body even if the body is only a single statement, but that's a matter of coding style. You can fix your code just by using block bodies for all your if statements, eg

if (GPer >= 88 && GPer <= 90)
{
   GPoint = 1.50;
   Des = "Very Good";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM