【问题标题】:Why is the else statement still printing after the if statement is satisfied?为什么 if 语句满足后 else 语句仍然打印?
【发布时间】:2013-05-21 08:26:36
【问题描述】:

抱歉,我是 * 的新手,但我在编码时遇到了问题。我创造了这个简单的 程序,但我注意到它在使用 if 语句完成后仍然打印 else 语句。代码是用 c++ 编写的,非常感谢您的帮助。

# include <iostream>
using namespace std;

int main()
{
    char check;
    bool done = false;
    while(not done)
    {
        cout<<"Please enter one of the options provided below."<<endl;
        cout<<"D = distance S = second F = first"<<endl;
        cin>>check;
        if(check == 'D')
        {
            cout<<"You pressed D"<<endl;
        }
        if(check == 'S')
        {
            cout<<"You pressed S"<<endl;
        }
        if(check == 'F')
        {
            cout<<"You pressed F"<<endl;
        }
        else
            cout<<"You suck!";
    }
    return 0;
}

例如,当我按 D 时,我只想接收 You pressed D 作为输出。相反,我得到You pressed D You suck!

【问题讨论】:

  • 它总是告诉你你很烂,除非你按 F。或者你期待别的什么? :)
  • 这是因为else属于最后一个if
  • 啊,谢谢!我自动假设 if 语句适用于所有 if 语句,而不仅仅是最后一个。 :D 我花了很多时间试图弄明白,这个网站在几秒钟内就回答了!
  • 使用单个switch 语句而不是一系列if else 语句。

标签: c++ if-statement


【解决方案1】:

我很确定您想要else if(即嵌套)而不是(后续)ifs,但这只是猜测,因为您没有提供输入或输出。

【讨论】:

    【解决方案2】:

    我认为仅发布确切的代码是最好的教育方式并不常见,但在这种情况下,我认为差异会突然出现:

       if(check == 'D')
        {
            cout<<"You pressed D"<<endl;
        }
        else if(check == 'S')
        {
            cout<<"You pressed S"<<endl;
        }
        else if(check == 'F')
        {
            cout<<"You pressed F"<<endl;
        }
        else
            cout<<"You suck!";
    

    确保您了解ifelse ifelse 之间的区别。

    这也是使用switch 语句代替的标准情况。

    【讨论】: