简体   繁体   English

If-else 语句不起作用

[英]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.但是,它只返回前两个选项 $0.50 和 $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-else 阶梯的开头。

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.第一种情况涵盖了 temp 小于 50 的所有场景。第二种情况涵盖了 temp 大于或等于 50 的所有部分。这涵盖了所有可能值的集合,因此不会执行其他子句。

The first else if doesn't have an upper bound for temp.第一个 else if 没有温度上限。
Change else if (temp >= 50) toelse if (temp >= 50)更改为
else if (temp >= 50 && temp < 61)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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