[英]Why while loop is printing one line?
I'm trying to print using C:我正在尝试使用 C 进行打印:
01010
01010
01010
01010
using nested loops and if only, I created this code:使用嵌套循环,如果只是,我创建了这个代码:
#include <stdio.h>
void main()
{
int n = 1, x = 0, count = 1, m = 0;
while (m <= 5)
{
while (n <= 5)
{
if (x == 0)
{
printf("%d", x);
x++;
}
else if (x == 1)
{
printf("%d", x);
x--;
}
n++;
}
m++;
}
}
But the output is 01010
one line only, may I know what's the reason and how should I fix it?但是output只有一行
01010
,请问是什么原因,应该如何解决?
I would do it like that:我会这样做:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; ++i)
{
for (int j = 0, x = 0; j < 5; ++j, x=!x)
printf("%d", x);
printf("\n");
}
}
Your problem is that the while
loop does not reset n
and x
.您的问题是
while
循环不会重置n
和x
。 A for
loop is better, it always starts with the initialization part before the first iteration. for
循环更好,它总是从第一次迭代之前的初始化部分开始。 To fix your code add x=0; n=1;
要修复您的代码,请添加
x=0; n=1;
x=0; n=1;
before while (n <= 5)
.在
while (n <= 5)
之前。
You also did not print a newline, so everything would be in the same line.您也没有打印换行符,因此所有内容都在同一行中。
Your if (x==0) x++; else if (x==1) x--;
你的
if (x==0) x++; else if (x==1) x--;
if (x==0) x++; else if (x==1) x--;
is the same as x =;x;
与
x =;x;
相同, from 0
to 1
and from 1
to 0
. , 从
0
到1
和从1
到0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.