为什么第二个数组写出愚蠢的数字? - C语言

时间:2018-03-05 18:45:14

标签: c arrays random

在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 个答案:

答案 0 :(得分:1)

1)不要打电话  第二次srand ( time(NULL) );。这将使用相同的数字重新启动生成器!!

2)a[j] = rand() % 10+1;范围有限。如果您可以将10增加到1001000.

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