简体   繁体   English

如何使用数字 1、2、3、4 生成随机 5 位数字并将这些生成的数字存储在 C 语言的数组中

[英]How to generate random 5 digit number using numbers 1,2,3,4 and store those generated numbers in array in C Language

I have to generate the random 5 digit number using 1,2,3,4 numbers and store generated numbers in array我必须使用 1、2、3、4 数字生成随机 5 位数字并将生成的数字存储在数组中

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

// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper, int count)
{
    int i;
    char str[45];
    char k[45];

    for (i = 0; i < count; i++)
    {
        int num = (rand() % (upper - lower + 1)) + lower;

        sprintf(str, "%d", num);
        strcat(str, k);
        printf("%d ", num);
    }

    printf("%d", k);
}

// Driver code
int main()
{
    int lower = 1, upper = 5, count = 5;

    // Use current time as
    // seed for random generator
    srand(time(0));

    printRandoms(lower, upper, count);

    return 0;
}

Expected Output:预期 Output:

[11111, 12343, 12123, 12121, 12323, 44444] [11111、12343、12123、12121、12323、44444]

You made 3 mistakes in your program:您在程序中犯了 3 个错误:

  1. With the function strcat , the first parameter is the destination string and the second parameter is the source string.对于 function strcat ,第一个参数是目标字符串,第二个参数是源字符串。 In your function call to strcat , you must therefore swap these two parameters.因此,在您对strcat的 function 调用中,您必须交换这两个参数。

  2. In contrast to strcpy , when using strcat , both parameters must be initialized strings, since you are appending one string to another string.strcpy相比,使用strcat时,两个参数都必须是初始化字符串,因为您将一个字符串附加到另一个字符串。 If you want the string (char array) k to be empty at the start and add a digit to it once per loop, you must initialize it to an empty string before the loop, for example by writing strcpy( k, "" );如果您希望字符串(字符数组) k在开始时为空并在每个循环中添加一个数字,则必须在循环之前将其初始化为空字符串,例如通过编写strcpy( k, "" ); or k[0] = '\0';k[0] = '\0';

  3. The line printf("%d",k);printf("%d",k); is wrong.是错的。 In order to print a string with printf, you must use %s instead of %d .为了使用 printf 打印字符串,您必须使用%s而不是%d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM