首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在一行中打印5个整数

无法在一行中打印5个整数
EN

Stack Overflow用户
提问于 2016-03-08 15:31:22
回答 4查看 125关注 0票数 0

我写了下面的代码。我想打印从0到49的数字,但不包括可除以7的数字。另外,一行将只打印5个数字。当我执行项目时,我得到的结果是

代码语言:javascript
复制
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

代码语言:javascript
复制
#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");
                   }
            }
        }

}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-03-08 15:50:46

您没有初始化count1,这段代码应该可以正常工作:

代码语言:javascript
复制
#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 
               }
        }
    }

}
票数 3
EN

Stack Overflow用户

发布于 2016-03-08 15:52:18

看看count1,它没有初始化,所以程序应该从分配给变量的内存中的一些垃圾开始。这就是为什么您的代码有这种奇怪的行为。

票数 1
EN

Stack Overflow用户

发布于 2016-03-08 15:53:01

将count1初始化为0。你可以在5个号码后得到新的行。因为如果不初始化,count1可能有任何值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35871491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档