无法理解有两个变量的循环 [英] Cannot understand for loop with two variables

查看:179
本文介绍了无法理解有两个变量的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在for循环中使用两个变量时,两个条件就像我在 i <3,j <2 时使用的那样,for循环一直执行到第二个条件失败。

  #include< iostream> 
#include< conio.h>
使用namespace std;
int main()
{
int i,j; (i = 0,j = 0; i <3,j <2; i ++,j ++)
{
cout <<
}
getch();
返回0;

$ / code>

在这段代码中, hello 打印2次。为什么?

如果我使用 i <3,j <10 ,则打印Hello10次。我不明白为什么第一个条件被忽略了。是依赖于编译器还是其他的东西?



如果我用||等条件替换, (OR)或者&(AND)。另外一个问题是,我不能在for循环中初始化i和j,它向我展示了一个错误,但是当我用C风格或者一个变量声明变量for循环,为什么是这样?

编译器我用过的是Orwell Dev C ++。
在此先感谢。

$ b (i = 0,j = 0; i <3,j <2; i ++,j ++)
解决方案 c $ c
$ b $ p $相当于
$ b $ for(i = 0,j = 0; j <2; i ++,j ++)



逗号表达式取最后一个表达式的值。 b
$ b

无论哪种情况第一,都会被忽略,而第二个只会用到。


When I use two variables in a for loop with different conditions two conditions like I have used below i<3,j<2 the for loop is always executing till the second condition fails.

#include<iostream>
#include<conio.h>
using namespace std ;
int main()
{
int i,j ;
for(i=0,j=0;i<3,j<2;i++,j++)
{
    cout<<"hello" ;
}
getch() ;
return 0 ;
} 

In that code, hello is printed 2 times. Why?

If I use i<3,j<10, "Hello" is printed 10 times. I can't understand why the first condition is being neglected. Is it compiler dependent or something else?

Every thing works normal if I replace with conditions like || (OR) or &&(AND).An other thing is that I cannot initialize i and j in the for loop itself, it is showing me an error, but works fine when I declare variables in C style or one variable outside the for loop, why is it so?

Compiler I have used is Orwell Dev C++.
Thanks in advance.

解决方案

for(i=0,j=0;i<3,j<2;i++,j++)

is equivalent to

for(i=0,j=0;j<2;i++,j++)

The comma expression takes on the value of the last expression.

Whichever condition is first, will be disregarded, and the second one will be used only.

这篇关于无法理解有两个变量的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆