我写了下面的代码。我想打印从0到49的数字,但不包括可除以7的数字。另外,一行将只打印5个数字。当我执行项目时,我得到的结果是
1 2 3
4 5 6 8 9
10 11 12 13 15
16 17 18 19 20
22 23 24 25 26
and so on我的问题是,为什么在3号之后添加新行?为什么第一行中只有3个元素?我正在使用codeblock + mingw
#include <stdio.h>
void main()
{
/*Program to declare 50 elements integer arrary; fill the array with number*/
int myarray[50];
int count;
int count1;
for(count=0;count<50;count++)
{
myarray[count]=count;
//printf("%d\t",count);
}
for(count=0;count<50;count++)
{
if((count%7)==0)
{
continue; // Do not print numbers divisible by 7
}
else
{
printf("%d\t",myarray[count]);
count1++;
// Print only 5 numbers per line
if((count1%5)==0)
{
printf("\n");
}
}
}
}发布于 2016-03-08 15:50:46
您没有初始化count1,这段代码应该可以正常工作:
#include <stdio.h>
void main()
{
/*Program to declare 50 elements integer arrary; fill the array with number*/
int myarray[50];
int count;
int count1=0; //initialisation
for(count=0;count<50;count++)
{
myarray[count]=count;
//printf("%d\t",count);
}
for(count=0;count<50;count++)
{
if((count%7)==0)
{
continue; // Do not print numbers divisible by 7
}
else
{
printf("%d\t",myarray[count]);
count1++;
if((count1/5)==0) // if the counter is 5 print a "\n"
{
printf("\n");
count1=0; // put count1 equal 0
}
}
}
}发布于 2016-03-08 15:52:18
看看count1,它没有初始化,所以程序应该从分配给变量的内存中的一些垃圾开始。这就是为什么您的代码有这种奇怪的行为。
发布于 2016-03-08 15:53:01
将count1初始化为0。你可以在5个号码后得到新的行。因为如果不初始化,count1可能有任何值。
https://stackoverflow.com/questions/35871491
复制相似问题