C ++ if-else if Issues

时间:2014-06-19 09:20:50

标签: c++ if-statement

我在下面的程序中遇到问题。它应该将1-100之间的数字转换为AA,BA,BB,CB,CC,D,F。但是如果我输入的数字少于84,它就会停止工作并显示“BA”。我检查了代码。但我不明白这是什么问题。

#include <iostream>
using namespace std;

int main() {
    int secenek,notu;
    cout << "Not Dönüştürücü" << endl;
    cout<<"Başlamak için 1'e basın:\n";
    cin>>secenek;

    if (secenek==1)
        {
        cout<<"Dönüştürülecek not: ";
        cin>>notu;
        }
        if (notu<0 || notu>100)
            {
            cout<<"Geçerli bir not girin.\n";
            }
        else if (notu>=90)
            {
            cout<<"AA";
            }
        else if (notu<90 || notu>84)
            {
            cout<<"BA";
            }
        else if (notu<85 || notu>79)
            {
            cout<<"BB";
            }
        else if (notu<80 || notu>74)
            {
            cout<<"CB";
            }
        else if (notu<75 || notu>69)
            {
            cout<<"CC";
            }
        else if (notu<70 || notu>59)
            {
            cout<<"D";
            }
        else if (notu<60)
            {
            cout<<"F";
            }
        }

4 个答案:

答案 0 :(得分:6)

你犯了一个逻辑错误:

else if (notu<90 || notu>84)

应该是

else if (notu<90 && notu>84)

同样适用于以下所有条件。

@ Jarod42建议

编辑;您甚至不需要再检查notu<90 ...您的代码可能如下所示:

if (notu<0 || notu>100)
    {
    cout<<"Geçerli bir not girin.\n";
    }
else if (notu>=90)
    {
    cout<<"AA";
    }
else if (notu>84)
    {
    cout<<"BA";
    }
else if (notu>79)
    {
    cout<<"BB";
    }
etc...

答案 1 :(得分:0)

你的病情

else if (notu<90 || notu>84)
无论notu设置为什么,

总是如此。你可能意味着

else if (notu < 90 && notu > 84)

答案 2 :(得分:0)

有问题的部分:

    else if (notu<90 || notu>84)
        {
        cout<<"BA";
        }
    else if (notu<85 || notu>79)
        {
        cout<<"BB";
        }
    else if (notu<80 || notu>74)
        {
        cout<<"CB";
        }

else if (notu<90 || notu> 84)会在低于90的任何notu和高于84的任何notu上触发。这几乎是所有在早期检查中幸存下来的人。

正确的实施将是else if (notu<90 && notu> 84),只有在满足两个条件时才会触发。

我的C ++有点生疏,但如果我没记错的话,甚至可以写else if (84 < notu < 90)。 编辑:else if (84 < notu < 90)不是有效的C ++语法。

答案 3 :(得分:0)

主要问题是您正在使用||,其中&&在逻辑上是正确的。

但是你真的不需要&& - 你可以简化一点,因为在else分支中你已经知道相应的if条件是假的。

像这样:

if (notu < 0 || notu > 100)
{
    cout << "Geçerli bir not girin.\n";
}
else if (notu >= 90)
{
    cout << "AA";
}
else if (notu >= 85) // Already know that it's < 90, because it's not >= 90
{
    cout << "BA";
}

// ...
// ...

else if (notu >= 60) // Already know that it's < 70
{
    cout << "D";
}
else   // Already know that it's < 60
{
    cout << "F";
}
相关问题