开发者

problem with generating rand number between 0 and 1 using C language

开发者 https://www.devze.com 2023-01-14 05:39 出处:网络
I am trying to generate some numbers with the rand() function like below: int main() { int i=0 for(i=0;i<20;i++)

I am trying to generate some numbers with the rand() function like below:

int main()
{
    int i=0
    for(i=0;i<20;i++)
    {
    printf("%f\n",rand_md());
    }
    return 0;
}



float rand_md()
{
    return (float)rand()/(RAND_MAX+1.0);
}

But when I run gcc rand.c, I get the error like below: rand.c: In function ‘main’: rand.c:21: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’ rand.c: At top level: rand.c:36: error: conflicting types for ‘rand_md’ rand.c:21: error: previou开发者_C百科s implicit declaration of ‘rand_md’ was here

What's wrong with my code?

Best Regards,


When you use a function without declaring it first, C will assume it returns an int. To fix this, you have to declare the method signature for rand_md before you call it in main().

Add something like this before main or in a header file:

float rand_md();


double rand_md()
{
    return (double )rand()/(RAND_MAX+1.0);
}

Now, rand_md returns a double instead of a float.

Also, since you haven't included it in your post, you should throw in a function prototype before main(). You also forgot to add a semicolon to int i = 0. The corrected code looks like this:

double rand_md();    

int main()
{
    int i=0;
    for(i=0;i<20;i++)
    {
    printf("%f\n",rand_md());
    }
    return 0;
}

double rand_md()
{
    return (double )rand()/(RAND_MAX+1.0);
}


You can use random(largest size of number) for this purpose.

0

精彩评论

暂无评论...
验证码 换一张
取 消