为什么在满足if语句之后,else语句仍然打印?

Why is the else statement still printing after the if statement is satisfied?

本文关键字:语句 打印 else 之后 满足 if 为什么      更新时间:2023-10-16

对不起,我是新的stackoverflow,但我有一个问题,而编码。我创建了这个简单的程序,但我注意到,它仍然打印else语句后,它与if语句。代码是用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!

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

我并不经常认为发布准确的代码是最好的教育方式,但在这种情况下,我认为区别会跳出来:

   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语句的标准情况。