简体   繁体   English

循环 C++ 中的条件语句

[英]conditional statement in loop c++

for (i = 1; i <= a; i++){
    for (b = 1; b <= i; b++){
        cout << "X";
    }
    cout << endl;
}

if a=4, the result would be如果 a=4,结果将是

X

XX

XXX

XXXX

while the output of this而这个输出

for (i = 1; i <= a; i++){
    for (b = 1; b <= a - i; b++){
        cout << "A";
    }
    cout << endl;
}

will be将会

AAA

AA

A

i recognize the different in conditional statement but i can not explain it my self why so.我认识到条件语句中的不同,但我无法解释为什么会这样。

For your first example, the first for loop with run because 1 is less than a (4).对于您的第一个示例,第一个 for 循环运行,因为 1 小于 (4)。 Which then it will move on to the next for loop.然后它将移动到下一个 for 循环。 So b = 1, and 1 equals to 1 which will run and print out X. Now that loop will end and the outer for loop will increment to 2, and repeat.所以 b = 1,并且 1 等于 1,它将运行并打印出 X。现在循环将结束,外部 for 循环将增加到 2,并重复。

Take a look at your stop conditions for the inner loops:查看内部循环的停止条件:

b <= i;
b <= a - i;

Now, let's start with i being 1:现在,让我们从i是 1 开始:

b <= 1;
b <= 3;

And, finish with i being 4:并且,以i为 4 结束:

b <= 4;
b <= 0;

Considering your b 's initializations:考虑到你的b的初始化:

b = 1;
b = 1;

Combine them all => your loop ranges for b s would be [1; 4]将它们全部结合起来 => b s 的循环范围将是[1; 4] [1; 4] and [3; 1] [1; 4][3; 1] [3; 1] . [3; 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM