首页 > 解决方案 > c++中的for循环条件问题?

问题描述

我正在使用模式程序,但面临一个问题,我的条件为假,然后条件运行?

模式程序:

#include<iostream>
using namespace std;
int main()
{
    int i,j,k,n;

    std::cout << "Enter Number:" ;
    cin>>n;

    for(int i=1;i<=n;i++)    //row 
    {
        //first time condition  false 1(k value)<1(i value) not execute first time this is ok
        //second time condition false 2(k value)<2(i value) why this condition run when condition is false????

        for(int k=1;k<i;k++) //space 
        {
            cout << " ";
        }

        for(int j=i;j<=n;j++)  //column
        {
                std::cout << "*" ;
        }
        cout << "\n";
    }
}

程序的执行:

例如:用户输入 3

第一次正确激发条件:

现在 i=1 和 k=1

  for(int i=1;1<=3;i++)    //row 
   {
        for(int k=1;1<1;k++) //space  //1<1 false  ok.
        {
           cout << " ";
        }

第二次条件的问题:

现在 i=2 和 k=2

  for(int i=1;2<=3;i++)    //row 
   {
        for(int k=1;2<2;k++) //space  //2<2 false  Not Ok problem is here why these condition is run
        {
           cout << " ";
        }

链接程序:https ://onlinegdb.com/Hk9DHuwvL

标签: c++

解决方案


i=2 and k=2,你的解释是错误的,正确的是:

当 时,循环i=2内部代码为:i

    for(int k=1;k<2;k++) //space, loops one time 
    {
        cout << " ";
    }

    for(int j=2;j<=3;j++)  //column, loops two times
    {
            std::cout << "*" ;
    }
    cout << "\n";

推荐阅读