c++ - 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 << " ";
}
解决方案
当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";
推荐阅读
- for-loop - 如何检查 X、Y 点是否在由 4 个 X、Y 点组成的正方形内?
- python - 带有`argparse`的AttributeError
- python - Pandas:提取列值,其中列名与另一列中的行值匹配
- r - 在“优化”R 函数中控制步长
- magento2 - 目录价格规则 Magento 2
- android-intent - Chromebook,意图过滤器从 Android 应用程序上的 gmail 应用程序下载附件
- java - SingleTon 类未同步并返回多个实例
- angular - 将自定义指令应用于表单
- elasticsearch - 对加密数据的模糊搜索
- pytorch - PyTorch Dataloader - 枚举时列表不可调用错误