否则没有先前的if c ++中的错误

时间:2014-03-12 16:07:34

标签: c++

有人可以在此代码中向我解释上述错误吗?我在CodeBlocks中得到它,当我使用Visual Studio它说预期一个声明。 非常感谢。

#include <iostream>
    using namespace std;
    int main()
    {
        char fruits;
        float sales;

        cout << " Enter the First letter of the Fruit's name : ";
        cin >> fruits;

        cout << " Enter the amount of sales : ";
        cin >> sales;


        if (fruits == 'A' || fruits == 'a')
            cout << " You are selling Apples ";
            cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";

        else if (fruits == 'P' || fruits == 'p')
            cout << " You are selling Pears";
            cout << " Your commission is " << sales*(5 / 100) << " rupees. ";

        else if (fruits == 'O' || fruits == 'o')
            cout << " You are selling Oranges ";
            cout << " Your commission is " << sales*(5.5 / 100) << " rupees. ";

        else if (fruits == 'G' || fruits == 'g')
            cout << " You are selling Grapes ";
            cout << " Your commission is " << sales*(6 / 100) << " rupees. ";

        else
            cout << " Invalid Entry. Try again. ";


        return 0;
    }

3 个答案:

答案 0 :(得分:5)

您需要在if语句中使用大括号,例如

if (fruits == 'A' || fruits == 'a') {
        cout << " You are selling Apples ";
        cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";
} else if (fruits == 'P' || fruits == 'p') {

} // and so on

因为否则你的if条款只对下一行有效,这会使你的逻辑看起来像这样:

if () 
    cout << " I am only getting executed if the above 'if' statement is true ";
cout << " I will always be executed, no matter what ";

并且,通过这样做,您的else语句将在代码中间松动,导致您获得的编译错误

if () 
    cout << " I am only getting executed if the above 'if' statement is true ";
cout << " I will always be executed, no matter what ";
else // but, else what? There is no 'if' behind me

答案 1 :(得分:4)

这是因为你有一个没有括号花括号的多行块。 C ++解释了这个

if (fruits == 'A' || fruits == 'a')
    cout << " You are selling Apples ";
    cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";
像这样:

if (fruits == 'A' || fruits == 'a')
    cout << " You are selling Apples "; // Protected by `if`
// Not protected by `if` !!!
cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";

C ++编译器忽略缩进;这就是为什么当您在第二个else之后放置cout时,它会被视为else而没有前一个if

要解决此问题,请将所有受if保护的块括在花括号中。即使在不需要大括号的情况下,养成习惯也是一个好主意,因为if会保护单个语句。

答案 2 :(得分:3)

在C ++中,代码

if (fruits == 'A' || fruits == 'a')
    cout << " You are selling Apples ";
    cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";

被解释为

if (fruits == 'A' || fruits == 'a') cout << " You are selling Apples ";
cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";

换句话说,if语句只保护第一个语句。第二个语句无条件执行。这解释了您收到的错误 - else if您与之前的if语句不匹配。

要解决此问题,请在if语句的正文周围添加大括号:

if (fruits == 'A' || fruits == 'a') {
    cout << " You are selling Apples ";
    cout << " Your commission is " << sales*(4.5 / 100) << " rupees. ";
}

更一般地说,缩进在C ++中是无关紧要的,所以要小心确保缩进符合预期的意图。

希望这有帮助!