创建一个动态数组并为其分配随机整数值?

时间:2016-10-23 04:29:52

标签: c arrays srand

int* create_array(char category, int n){
  int *a;

  a = malloc(n* sizeof(int));

  for (int i = 0; i < n; i++) {
    int x;
    srand( time(NULL));
    x = rand();
    a[i] = x;
  }

当我打印此代码时,它只会打印相同的随机变量'n'次。

2 个答案:

答案 0 :(得分:0)

您可以使用you have to put names of your columns in you sql query $save = mysql_query("INSERT INTO `user`(``, ``, ``, ``, ``, ``, ``, ``) VALUES('', '$nama', '$user', '$pass', '$date', '$mail', '$tlp', '$permit')"); $gets = mysql_query("INSERT INTO `user_pack`(``, ``, ``, ``, ``, ``, ``, ``, ``, ```, ``, ``, ``, ``) VALUES('', '$pack_name', '$user', '$start', '$end', '0', '$limit', '$price', '$permiti', '$encrypts', '$invoice', '$start_date', '$end_date', '0')"); 或者您可以使用0到10生成的srand(getpid()指定其他随机数范围;

答案 1 :(得分:0)

您可以尝试这样的事情:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int *create_array(char category, int n);

int
main(int argc, char const *argv[]) {
    time_t t;
    int *array;
    int i, n;
    char category;

    srand((unsigned)time(&t));

    printf("Enter category: ");
    if (scanf("%c", &category) != 1) {
        printf("Invalid category.\n");
        exit(EXIT_FAILURE);
    }

    printf("Enter n numbers: ");
    if (scanf("%d", &n) != 1) {
        printf("Invalid n value.\n");
        exit(EXIT_FAILURE);
    }

    array = create_array(category, n);

    printf("Your n random numbers between 0-10:\n");
    for (i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }

    free(array);

    return 0;
}

int
*create_array(char category, int n) {
    int *array;
    int i, candidate;

    array = malloc(n * sizeof(*array));

    for (i = 0; i < n; i++) {
        candidate = rand() % 10;
        array[i] = candidate;
    }

    return array;
}