[英]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.