C語言中的例子--偽隨機數

salt4172發表於2014-11-12

# include <stdio.h>
# include <stdlib.h>
# include <time.h>
int main (void)
{
        srand((unsigned)time(NULL));
        int i;
        for (i=0;i<10;i++)
               printf("%4i",rand()%100+1);

        printf("\n");
        return 0;
}
測試結果:

root@localhost Gcc]# ./a.out
  31   8  28  31  53  21   7  19  34  76

//rand()0+1 表示(0,100]

 

使用動態大小陣列函式呼叫:
# include stdio.h>
# include stdlib.h>
# include time.h>
int main (void)
{
        int n;
        srand((unsigned)time(NULL));
        printf("Enter a number n : ");
        scanf("%i",&n);
        int arr[n];
        printArray(n,arr);
        return 0;
}
int printArray(int n, int a[])
{
        int i;
        for (i=0;i < n ;i++)
                a[i] = rand()%100+1;
        for (i=0;i
                printf("%4i",a[i]);
        printf("\n");
}

測試結果:

[root@localhost Gcc]# ./a.out
Enter a number n : 10
  17  34  89  88   1  19  22   9  87  44
[root@localhost Gcc]# ./a.out
Enter a number n : 20
  23  68  87  95  25  75  86  90   7   7  95  27  35  25   9  84  54  45  51   5

相關文章