简体   繁体   English

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

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

Why does my first if statement work, but my else if statement doesn't? 为什么我的第一个if语句有效,而我的if语句却无效? Just hoping someone can see something I may be missing. 只是希望有人能看到我可能会丢失的东西。 When I enter in a time between 800 and 1800 the code continues fine, but when I enter in 600 it jumps to my else statement that I entered in an illegal format. 当我输入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))

You've got a 'logic bug' : use || 您有一个“逻辑错误” :使用|| instead of && in else if . 而不是&&else if It's simply impossible for a number to be less than 800 and greater than 1800 at the same time . 这是根本不可能的数量要小于800和大于1800 在同一时间

As soon as I asked this question I realized my second else if statement should be an or || 我一问到这个问题,我就意识到我的第二个if语句应该是or或||。 statement instead of &&. 语句而不是&&。

change 更改

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

to

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

You can simplify the code to this, else statement is not needed. 您可以将代码简化为此,否则不需要语句。 Store the value in coeficient variable, that's needed to be defined before 将值存储在系数变量中,这需要在定义之前

// 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