我写了下面的代码。我想打印 0到49 中的数字,但不包括可被7整除的数字。在一行中只打印5个数字。当我执行项目时,我得到的结果是
The Performance.now()
我的问题是为什么新号码会在号码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个元素?我正在使用codeblock + mingw
3
答案 0 :(得分:3)
您没有初始化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
}
}
}
}
答案 1 :(得分:1)
看看count1
,它没有被初始化,所以程序应该从分配给变量的内存中的一些垃圾开始。这就是为什么你的代码有这种奇怪的行为。
答案 2 :(得分:1)
将count1初始化为0。 你可以在5个数字后获得新的一行。 因为如果你没有初始化count1可能有任何价值。
答案 3 :(得分:0)
您的变量count1
未初始化。
此外,您可以将代码缩短为1循环。
更简单的方法是:
int myarray[50];
int number = 0; // number from 0 to 49
int index = 0; // index of the array, only increments when a valid number is found
for(number;number<50;number++) // iterate from 0 to 49
{
if(number % 7 != 0){ // if number is not divisible by 7
myarray[index]=number; // add the number to the array
printf("%d ", number); // print the number
if(index % 5 == 0){ // if 5 numbers have been added, print a \n
printf("\n");
}
index++; // increment index
}
}