在 C 中使用 rand() 时的 c4014

标签 c random warnings srand

我正在尝试使用 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/

相关文章:

c - C POSIX 中的 FTP url 正则表达式

c - 有没有比在 C 中使用 rb_funcall() 更惯用的方法来初始化 Ruby 对象?

java - 生成无溢出的安全随机 double

ios - 如何避免核心数据警告 "Entity should have an inverse relationship"?

javascript - jquery - 动态地将div添加到子级

c - 我该怎么做才能使我的程序在 do while 循环中保持在开关中输入的最小数字?

c - OpenCV 将坐标传递给 OpenGL 但 OpenGL 无法绘制它

javascript - 在 JavaScript Math.Floor((Math.Random() * 1) + 0) 中得到 1 的概率

java - 在 Java 中使用随机运算符创建最小值

c# - resharper 协变数组转换 - 矛盾修复