为什么我的第一个 if 语句有效,但我的 else if 语句在它之后不起作用



为什么我的第一个if语句工作,但我的else 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中使用||而不是&&

不可能同时小于800又大于1800

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

一个数字不可能既小于800又大于1800。我想你的意思是:

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

当我问这个问题时,我意识到我的第二个else if语句应该是or ||语句,而不是&&

change

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

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

您可以将代码简化为这样,不需要使用else语句。将值存储在需要在

之前定义的系数变量中
// 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;

最新更新