为了账号安全,请及时绑定邮箱和手机立即绑定

两个if和下面cout代码的顺序有影响没,老师为啥没有按1,2,3,4,5,的顺序给出代码,而是先把两个判断提前了?


好心的小伙伴帮忙看看代码

https://img1.sycdn.imooc.com//5b66a4410001b81209500561.jpg

正在回答

5 回答

顺序有影响,如果交换两个if{},空字符串时也会打印三个cout。

0 回复 有任何疑惑可以回复我~

代码 执行顺序都是从上到下  从左到右的顺序执行,在 java 中我知道 他有时候代码执行顺序会受到影响 然而你如果按照题中要求进行一步一步进行代码编写 也不是不可能。 但是有可能增加不必要的步骤

0 回复 有任何疑惑可以回复我~
第一个有影响,如果输入空字符串,会执行判断中的return 0,不会有后面的输出;

第二个判断只会影响是否输出"you are a administrator." 和后面的无关


一般先判断条件在执行操作,这个属性编程习惯吧。比如有些条件不满足则操作不同

0 回复 有任何疑惑可以回复我~
#include <iostream>
#include<string>
using namespace std;
int main()
{
    cout << "pleas enter your name" << endl;
    string s1;
    getline(cin, s1);
    if (s1.empty())
    {
        cout << "this is empty" << endl;
        return 0;
    }
    cout << "hello " << s1 << endl;
    if (s1 == "imooc")
    {
        cout << "you are the admin" << endl;
    }
    cout << "your name is : " << s1.size() << " characters" << endl;
    cout << "the first character of you name is : " << s1[0] << endl;
    return 0;

}


1 回复 有任何疑惑可以回复我~
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

int main(){
    string name;
    cout<< "Please input your name:" << endl;
    getline(cin,name);
    if (name.empty()){
        cout <<"input is NULL." << endl;
        system("pause");
        return 0;
    }

    if (name == "imooc"){
        cout << "you are a administrator." << endl;
    }

    cout << "hello " + name << endl;
    cout << "the length of your name:" << name.size() <<endl;
    cout << "the first letter of your name:" << name[0] <<endl;
    system("pause");
    return 0;
}


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之封装篇(上)
  • 参与学习       103381    人
  • 解答问题       732    个

封装--面向对象的基石,本教程力求帮助小伙伴们即学即会

进入课程

两个if和下面cout代码的顺序有影响没,老师为啥没有按1,2,3,4,5,的顺序给出代码,而是先把两个判断提前了?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号