我在 2 个数组中创建随机数时遇到了一些问题。第一个数组可以很好地创建随机数,但另一个数组总是创建相同的数字,尽管有时会更改它们,例如。 10 10 10 10 10 10 等等...但是当我再次运行程序时它显示 7 7 7 7 7 等等...
这是程序:
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
main()
{
srand ( time(NULL) );
int i,j,switchh,switching;
int howmany = 10;
int a[howmany],b[howmany];
for (i=0;i<howmany;i++) {
b[i] = rand() % 10+1;
}
while(1) {
switchh=0;
for (i=0; i<howmany-1;i++) {
if (b[i]>b[i+1]) {
int switching=b[i];
b[i]=b[i+1];
b[i+1]=switching;
switchh = 1;
}
}
if(switchh==0) {
break;
}
}
srand ( time(NULL) );
for (j=0;j<howmany;j++) {
a[j] = rand() % 10+1;
}
while(1) {
switchh=0;
for (j=0; j<howmany-1;j++) {
if (a[j]>a[j+1]) {
int switching=a[j];
a[j]=a[j+1];
a[j+1]=switching;
switchh = 1;
}
}
if(switchh==0) {
break;
}
}
for (j=0;j<howmany;j++) {
printf("%d\n",a[i]);
}
for (i=0;i<howmany;i++) {
printf("%d\n",b[i]);
}
return 0;
}
最佳答案
1) 不要打电话
srand ( time(NULL) );
第二次。这将使用相同的数字重新启动生成器!!
2) a[j] = rand() % 10+1;
范围有限。如果您可以将 10
增加到 100
或 1000。
3)打印输出错误:
for (j=0;j<howmany;j++) {
printf("%d\n",a[i]); // change to a[j];
}
程序:
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
int main()
{
srand ( time(NULL) );
int i,j,switchh,switching;
int howmany = 10;
int a[howmany],b[howmany];
for (i=0;i<howmany;i++) {
b[i] = rand() % 10 +1;
}
while(1)
{
switchh=0;
for (i=0; i<howmany-1;i++) {
if (b[i]>b[i+1]) {
int switching=b[i];
b[i]=b[i+1];
b[i+1]=switching;
switchh = 1;
}
}
if(switchh==0) {
break;
}
}
// srand ( time(NULL) );
for (j=0;j<howmany;j++) {
a[j] = rand() % 10+1;
}
while(1) {
switchh=0;
for (j=0; j<howmany-1;j++) {
if (a[j]>a[j+1]) {
int switching=a[j];
a[j]=a[j+1];
a[j+1]=switching;
switchh = 1;
}
}
if(switchh==0) {
break;
}
}
for (j=0;j<howmany;j++) {
printf("%d\n",a[j]);
}
printf(" \n");
for (i=0;i<howmany;i++) {
printf("%d\n",b[i]);
}
return 0;
}
输出:
1
2
2
3
5
6
7
8
8
9
3
3
4
5
6
6
8
8
9
9
关于c - 为什么第二个数组写的是愚蠢的数字? - C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117407/