我正在尝试使用 C 中的 rand() 函数让我的程序返回一个随机数 [-5,5]。该程序正在运行,但我不喜欢每次编译代码时它都会发出 2 个警告。 这是代码:
#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;
}
这些是警告:
warning C4013: 'srand' undefined; assuming extern returning int
warning C4013: 'rand' undefined; assuming extern returning int
为什么会出现这些警告?我担心它们可能会在以后引起一些问题,所以我想消除这些警告。
编辑:
添加了另一个库:
#include <stdlib.h>
2 个警告消失,1 个新警告:
warning C4244: 'function' : conversion from 'time_t' to 'unsigned int', possible loss of data
通过更改 srand 调用解决了新警告:
srand((unsigned int)time(NULL));
这是最终解决的程序:
#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;
}
已解决,逐步显示编辑内容,以供其他用户将来引用。 谢谢
最佳答案
您需要包含stdlib.h
。这就是定义这些函数的地方。
关于在 C 中使用 rand() 时的 c4014,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110182/