![](/img/trans.png)
[英]How do I make a function print out a certain amount of Random numbers through the command line? C
[英]How do I print x amount of integers per line in C?
如何使用 while 循环和counter
变量x
打印从 1 到 20 的integers
。
我只需要每行打印五个整数。 [提示:使用x % 5
的计算。 当 this 的值为0
时,打印一个换行符( \n
),否则打印一个制表符( \t
)]
我的主要问题是:如何每行打印 5 个整数?
这是我尝试过的代码
#include<stdio.h>
int main ( void )
{
int x = 0;
while ( x <= 20 )
{
printf("%d", x);
++x;
}
}
使用 while 循环和计数器变量 x 打印从 1 到 20 的整数。
但是您的代码打印从0到 20 的整数,替换int x = 0;
通过int x = 1;
使用计算
x % 5
。 当 this 的值为 0 时,打印一个换行符,否则打印一个制表符。
在 C 中直接表示
putchar((x%5) ? '\t' : '\n');
或在printf
中做
printf("%d%c", x, (x%5) ? '\t' : '\n');
所以最后你的代码可以是:
#include<stdio.h>
int main (void)
{
int x = 1;
while ( x <= 20 ) {
printf("%d%c", x, (x%5) ? '\t' : '\n');
++x;
}
}
编译和执行:
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 $
% 是模运算。 a % b integer a 除以 b 并返回余数。 因此 3 % 5 -> 3 和 7 % 5 -> 2。
您有变量 x,它应该 go 从 0 到 19。如果将 x 除以 5,则提示将是 0 到 4 范围内的数字。
对于 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,...
如您所见,余数重复从 0 到 4 的数字。这些是 5 个数字。
所以诀窍是仅当 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.