在c中生成随机代码

Ada*_*ent 1 c barcode

我正在尝试生成一个随机的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;

}
Run Code Online (Sandbox Code Playgroud)

sel*_*bie 7

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

这一行:

printf("%d",barcode);
Run Code Online (Sandbox Code Playgroud)

基本上将地址打印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]);
Run Code Online (Sandbox Code Playgroud)

但也许更好的方法是生成一串字符而不是整数数组.代码的快速修改是'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;
}
Run Code Online (Sandbox Code Playgroud)

以上将产生10位数代码,第一个数字为前导零的可能性很小.如果那不是你想要的,那就是一个简单的bug修复.(我会留给你的......)