[英]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: 我正在尝试使用rand()函数生成一些数字,如下所示:
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 但是当我运行gcc rand.c时,出现如下错误:rand.c:在函数'main'中:rand.c:21:警告:格式'%f'期望类型为'double',但是参数2为类型'int'rand.c:最高层:rand.c:36:错误:'rand_md'的类型冲突rand.c:21:错误:先前的'rand_md'隐式声明在这里
What's wrong with my code? 我的代码有什么问题?
Best Regards, 最好的祝福,
When you use a function without declaring it first, C will assume it returns an int
. 当您使用函数而不先声明时,C会假定它返回一个
int
。 To fix this, you have to declare the method signature for rand_md
before you call it in main()
. 要解决此问题,必须在
main()
调用rand_md
之前声明方法签名。
Add something like this before main
or in a header file: 在
main
或头文件中添加以下内容:
float rand_md();
double rand_md()
{
return (double )rand()/(RAND_MAX+1.0);
}
Now, rand_md
returns a double
instead of a float
. 现在,
rand_md
返回double
而不是float
。
Also, since you haven't included it in your post, you should throw in a function prototype before main()
. 另外,由于您没有在帖子中添加它,因此应该在
main()
之前插入一个函数原型。 You also forgot to add a semicolon to int i = 0
. 您还忘记了将分号添加到
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);
}
您可以为此使用随机数(最大数字)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.