简体   繁体   中英

If-else statement not working

I am trying to set the price depending on a randomly generated temperature. However, it only returns the first two options $0.50 and $0.55. I am pretty sure it has something to do with the && statements but I'm not entirely sure why it isn't working.

public static double GetPrice ()
{
    if (temp < 50)
    {
        price = 0.50;
    }
    else if (temp >= 50)
    {
        price = 0.55;
    }
    else if (temp >= 61 && temp <= 65)
    {
        price = 0.60;
    }
    else if (temp >= 66 && temp <= 70)
    {
        price = 0.65;
    }
    else if (temp >= 71 && temp <= 75)
    {
        price = 0.75;
    }
    else if (temp >= 76 && temp <= 80)
    {
        price = 0.80;
    }
    else if (temp >= 81 && temp <= 85)
    {
        price = 0.85;
    }
    else if (temp >= 86 && temp <= 90)
    {
        price = 0.90;
    }
    else if (temp > 90)
    {
        price = 1.00;
    }

    return price;
}

change the first two conditions to

if (temp >=0 && temp < 50)
    {
        price = 0.50;
    }
    else if (temp >= 50 && temp < 61)
    {
        price = 0.55;
    }

因为前两个分支无论哪种方式都是正确的。

Look at the beginning of your if-else ladder.

if (temp < 50)
{
    price = 0.50;
}
else if (temp >= 50)
{
    price = 0.55;
}

The first case covers all the scenario where temp is less than 50. The second case covers all the parts where temp is greater than or equal to 50. This covers the set of all possible values and so no other clause gets executed.

The first else if doesn't have an upper bound for temp.
Change else if (temp >= 50) to
else if (temp >= 50 && temp < 61)

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