我在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