【发布时间】:2020-03-23 00:09:11
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, n;
printf("\n%s\n%s",
"Some randomly distributed integers will be printed.",
"How many do yo want to see? ";
scanf("%d", &n);
for (i = 0; i < n; ++i) {
if (i % 10 == 0)
putchar('\n');
printf("%7d", rand());
}
printf("\n\n");
return 0;
}
这是教科书“A book on C”中的代码。
当您在提示时输入 23 时,它应该会生成 3 行 8 列 (3*8-1) 中的 23 个随机数。
我了解到printf("%7d", rand())应该返回一个以十进制整数格式打印的值,并且打印整数的字段的宽度是7。
但是,我得到了宽度超过 7 的随机数,而且它看起来一点也不整洁。 (没有列也没有行,只有一大块连续的数字,比如 1235289043528935294835698246182965982)
我认为这与表达式 printf("%7d", rand()) 函数以及它应该如何返回值的方式有关。
我开始认为教科书是错误的。
【问题讨论】:
-
将
n作为参数会更常见。例如int main(int argc, char *argv) { int i, n = argc > 1 ? strtol(argv[1], NULL, 10) : 10;,然后使用参数调用程序。 (例如./a.out 23)
标签: c random c-standard-library