如何在 C 两个冒号中生成随机数?

How to generate random numbers in C two colons?

我需要在 c 代码中生成两个水平方向的数字...这样我就可以为我的登录系统获取令牌号。

我需要得到这个:

token=0.152644,0.429187

所以在示例中我有 token= 和随机生成的数字,它们以 0 开头,然后是 6 个随机生成的数字,用 , 符号分隔。 如何在 C 中得到这个?

我试过这段代码,但它没有给我想要的_

#include <stdio.h>
#include <string.h>

typedef
union
{
    char tmp[sizeof(unsigned long long)];
    unsigned long long myll;
} ll_t;


unsigned long long llrand(void)
{
    FILE *in=fopen("/dev/urandom", "r");
    ll_t ll_u;
    fread(ll_u.tmp, sizeof(ll_u.tmp), 1, in);
    fclose(in);
    return ll_u.myll;
}

int main()
{
    char tmp1[64]={0x0};
    char working[64]={0x0};
    int i=0;

    for(i=0; i< 1; i++)
    {
        while(strlen(tmp1) < 6)
        {
            sprintf(working, "%lu", llrand() );
            strcat(tmp1, working);
        }
        tmp1[6]=0x0;

        printf("%s\n", tmp1);
        *tmp1=0x0;
     }
    return 0;
 }

从输出我得到这个:

747563
102595

代码能不能简单短点?

这是运行完美的代码:

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

int main() {
  int n1, n2;
  time_t t;  

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

    n1 = rand() % 1000000 + 1;
    n2 = rand() % 1000000 + 1;

    printf("token=0.%d,0.%d\n", n1, n2);

  return 0;
}

输出为:

token=0.289384,0.930887 

您可以使用 rand() 函数:

#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int randomNumber(int min, int max)
{
    /* generate secret number between min and max: */
    int res = rand() % (max-min+1) + min;
    return res;
}

int main()
{
    int i = 0;
    srand (time(NULL));
    for (i=0; i<100; i++)
        printf("%d ", randomNumber(10, 1000000));
    return 0;
}

这是 rand() 的完整细节: http://www.cplusplus.com/reference/cstdlib/rand/

A 提出不同的方法。不要生成 2 个数字并将它们格式化为输出字符串,而是生成 12 个不同的数字并将它们直接放在适当的位置。

srand(time(0));
char output[] = "taken=0.XXXXXX,0.YYYYYY";
for (int n = 0; n < 2; n++) {
    for (int k = 0; k < 6; k++) {
        output[9 * n + 8 + k] = rand() % 10 + '0';
        // you might want to write a function that deals with rand() bias
    }
}
puts(output);