[英]c4014 when using rand() in C
I'm trying to make my program return a random number [-5,5] using rand() function in C. The program is working but I dont like the fact its giving 2 warning everytime i compile the code. 我正在尝试使用C中的rand()函数使程序返回一个随机数[-5,5]。该程序正在运行,但我不喜欢每次我编译代码时都给出2警告的事实。 Here is the code:
这是代码:
#include <time.h>
#include<stdio.h>
int main(int argc, char *argv[]){
int randomNumber = 0;
for (int index = 1; index < argc; index++) {
printf("The %d is %s\n", index, argv[index]);
}
getchar();
srand(time(NULL));
randomNumber = (rand()%11)-5;
return randomNumber;
}
And these are the warnings: 这些是警告:
warning C4013: 'srand' undefined; assuming extern returning int
warning C4013: 'rand' undefined; assuming extern returning int
Why are these warnings showing up?I'm afraid they might cause some problem later so I would like to eliminate those warnings. 为什么会出现这些警告?恐怕稍后可能会引起一些问题,因此我想消除这些警告。
Edits: 编辑:
Added another library: 添加了另一个库:
#include <stdlib.h>
2 warnings gone, 1 new one: 2条警告消失,1条新警告:
warning C4244: 'function' : conversion from 'time_t' to 'unsigned int', possible loss of data
New warning solved by change in the srand call to: 通过更改对srand的调用解决了新的警告:
srand((unsigned int)time(NULL));
This is the final and solved program: 这是最终的解决方案:
#include <time.h>
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int randomNumber = 0;
for (int index = 1; index < argc; index++) {
printf("The %d is %s\n", index, argv[index]);
}
getchar();
srand((unsigned int)time(NULL));
randomNumber = (rand()%11)-5;
return randomNumber;
}
SOLVED,showed the edits step by step for future reference to other users. 已解决,逐步显示了编辑内容,以供将来其他用户参考。 Thanks
谢谢
You need to include stdlib.h
. 您需要包括
stdlib.h
。 That is where those functions are defined. 这就是定义这些功能的地方。
You're getting this warning because the functions rand
and srand
haven't been defined. 您收到此警告是因为尚未定义函数
rand
和srand
。
From the man page: 从手册页:
NAME rand, rand_r, srand - pseudo-random number generator
NAME rand,rand_r,srand-伪随机数生成器
SYNOPSIS
概要
#include <stdlib.h> int rand(void); int rand_r(unsigned int *seedp); void srand(unsigned int seed);
By including stdlib.h, you get the prototypes for these functions, and the compiler can ensure you're calling them correctly. 通过包含stdlib.h,您可以获得这些函数的原型,并且编译器可以确保正确调用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.