首页 > 解决方案 > 在c中生成随机码

问题描述

我正在尝试生成一个随机的 10 位代码,但即使我使用代码中每个数字的绝对值,它有时仍会打印一个负值

#include <stdio.h>

int main()
{
    int i;
    int r;
    int barcode[11];
    srand(time(NULL));
    for(i=0;i <= 10;i++){
        r = rand() % 10;
        barcode[i] = abs(r);
    }
    printf("%d",barcode);
    return 0;

}

标签: cbarcode

解决方案


因为您实际上是在打印整数数组的地址,而不是字符串。

这一行:

printf("%d",barcode);

基本上将地址打印barcode为有符号整数而不是条形码的内容。

你当然可以这样做:

printf("%d%d%d%d%d%d%d%d%d%d",barcode[0], barcode[1], barcode[2], barcode[3], barcode[4], barcode[5], barcode[6], barcode[7], barcode[8], barcode[9]);

但也许更好的方法是生成字符串而不是整数数组。对您的代码进行快速修改是'0'在循环的每次交互中添加到每个随机值并附加到 char 数组。

int main()
{
    int i;
    int r;
    char barcode[11];          // array of chars instead of ints
    srand(time(NULL));
    for(i=0; i < 10; i++)      // loop 10 times, not 11
    {
        r = rand() % 10;
        barcode[i] = '0' + r;  // convert the value of r to a printable char
    }
    barcode[10] = '\0';        // null terminate your string
    printf("%s\n",barcode);
    return 0;
}

以上将生成一个 10 位代码,第一个数字很可能是前导零。如果这不是您想要的,那是一个简单的错误修复。(我将留给你...)


推荐阅读