简体   繁体   中英

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

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: previous 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);
}

您可以为此使用随机数(最大数字)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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