繁体   English   中英

为什么我的第一个if语句起作用,但是我的其他if语句不起作用

[英]Why does my first if statement work, but my else if statement after it doesn't work

为什么我的第一个if语句有效,而我的if语句却无效? 只是希望有人能看到我可能会丢失的东西。 当我输入800到1800之间的代码时,代码仍然可以正常运行,但是当我输入600时,它跳转到我的else语句,即我以非法格式输入了代码。

if ((time_start >= 800) && (time_start <= 1800))
    {
    cout << "How many minutes did your call last? ";
    cin >> minutes;
    cost = minutes * 0.40;
    cout << setprecision(2) << fixed << cost;
    system("pause");
    keepgoing = false;
} 
else if ((time_start < 800) && (time_start > 1800))
{
    cout << "How many minutes did your call last? ";
    cin >> minutes;
    cost = minutes * 0.25;
    cout << setprecision(2) << fixed << cost;
    system("pause");
    keepgoing = false;
}

else if ((time_start < 800) && (time_start > 1800))

一个数字不可能小于800且大于1800。我假设您的意思是:

else if ((time_start < 800) || (time_start > 1800))

您有一个“逻辑错误” :使用|| 而不是&&else if 这是根本不可能的数量要小于800和大于1800 在同一时间

我一问到这个问题,我就意识到我的第二个if语句应该是or或||。 语句而不是&&。

更改

否则如果((time_start <800)(time_start> 1800

否则((time_start <800)||(time_start> 1800

您可以将代码简化为此,否则不需要语句。 将值存储在系数变量中,这需要在定义之前

// else coef (default value)
float coef = 0.25;
if ((time_start >= 800) && (time_start <= 1800))
{
    coef = 0.40; // if true
}
cout << "How many minutes did your call last? ";
cin >> minutes;
// use coef here and remove duplicate calls
cost = minutes * coef;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;

暂无
暂无

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

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