简体   繁体   English

如何在 C 中每行打印 x 个整数?

[英]How do I print x amount of integers per line in C?

How to print the integers from 1 to 20 using a while loop and the counter variable x .如何使用 while 循环和counter变量x打印从 1 到 20 的integers

I need to print only five integers per line.我只需要每行打印五个整数。 [ Hint : Use the calculation x % 5 . [提示:使用x % 5的计算。 When the value of this is 0 , print a newline character ( \n ), otherwise print a tab character ( \t )]当 this 的值为0时,打印一个换行符( \n ),否则打印一个制表符( \t )]

My main question is: How to print 5 integers per line?我的主要问题是:如何每行打印 5 个整数?

This is the code i have tried这是我尝试过的代码

#include<stdio.h>

int main ( void )
{
    int x = 0;
    while ( x <= 20 ) 
    {
        printf("%d", x);
        ++x;
    }
}

Print the integers from 1 to 20 using a while loop and the counter variable x.使用 while 循环和计数器变量 x 打印从 1 到 20 的整数。

but your code print the integers from 0 to 20, replace int x = 0;但是您的代码打印从0到 20 的整数,替换int x = 0; by int x = 1;通过int x = 1;

Use the calculation x % 5 .使用计算x % 5 When the value of this is 0, print a newline character, otherwise print a tab character.当 this 的值为 0 时,打印一个换行符,否则打印一个制表符。

in C that directly means在 C 中直接表示

putchar((x%5) ? '\t' : '\n');

or doing in the printf或在printf中做

printf("%d%c", x, (x%5) ? '\t' : '\n');

so finally your code can be:所以最后你的代码可以是:

#include<stdio.h>

int main (void)
{
  int x = 1;
  
  while ( x <= 20 ) {
    printf("%d%c", x, (x%5) ? '\t' : '\n');
    ++x;
  }
}

Compilation and execution:编译和执行:

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
pi@raspberrypi:/tmp $ 

% is the modulo operation. % 是模运算。 a % b integer divide a by b and return the remainder. a % b integer a 除以 b 并返回余数。 Thus 3 % 5 -> 3 and 7 % 5 -> 2.因此 3 % 5 -> 3 和 7 % 5 -> 2。

You have the variable x which should go from 0 to 19. If you divide x by 5, the reminder will be a number in the range 0 to 4.您有变量 x,它应该 go 从 0 到 19。如果将 x 除以 5,则提示将是 0 到 4 范围内的数字。

For x = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ..., x % 5 = 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1,...对于 x = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ..., x % 5 = 0, 1, 2, 3, 4, 0, 1, 2 , 3, 4, 0, 1,...

As you can see, the remainder repeats the numbers from 0 to 4. These are 5 numbers.如您所见,余数重复从 0 到 4 的数字。这些是 5 个数字。

So the trick is to print a new line only when x % 5 equals 4.所以诀窍是仅当 x % 5 等于 4 时才打印新行。

int x = 0;
while (x < 20) {
    printf("%d ", x+1);
    if (x % 5 == 4)
        printf("\n");
    x++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM