首页 > 解决方案 > “错误:函数 'srand' 的隐式声明在 C99 中无效” 添加 stdlib.h 标头可消除此错误,但为什么呢?

问题描述

最初,我的文件中没有 stdlib.h 标头,并且在 VS Code 上出现错误,但代码对我来说似乎是正确的,并且我解决了任何其他现有错误,因此我将代码复制并粘贴到在线编译器上(不添加 stdlib.h 标头)并且代码运行良好。这是因为我可能只是在我的计算机上为 VS Code 安装了一个旧的或坏的工具集吗?我有下面写的程序:

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

main()
{
    int dice1, dice2;
    int total1, total2;
    time_t t;
    char ans;

    //Remember that this is needed to to make sure each random number
    //generated is different

    srand(time(&t));

    //This would give you a number between 0 and 5, so the + 1
    //makes it 1 to 6

    dice1 = (rand() % 5) + 1;
    dice2 = (rand() % 5) + 1;
    total1 = dice1 + dice2;
    printf("First roll of the dice was %d and %d, ", dice1, dice2);
    printf("for a total of %d.\n\n\n", total1);

    //Asks you to make a guess for your next roll.

    do 
    {
        puts("Do you think the next roll will be ");
        puts("(H)igher, (L)ower, or (S)ame?\n");
        puts("Enter H, L, or S to reflect your guess.");

        scanf(" %c", &ans);
        ans = toupper(ans);
    }

    while ((ans != 'H') && (ans != 'L') && (ans != 'S'));

    //Roll the dice a second time to get your second total

    dice1 = (rand() % 5) + 1;
    dice2 = (rand() % 5) + 1;
    total2 = dice1 + dice2;

    //Display the second total for the user 

    printf("\nThe second roll was %d and %d, ", dice1, dice2);
    printf("for a total of %d.\n\n\n", total2);

    //Now compare the two dice totals against the users guess
    //and tell them if they were right or not

    if (ans == 'L')
    {
        if (total2 < total1)
        {
            printf("Good job! You were right!\n");
            printf("%d is lower than %d\n", total2, total1);
        }

        else
        {
            printf("Sorry! %d is not lower than %d\n\n", total2, total1);
        }
    }

    else if (ans == 'H')
    {
        if (total2 > total1)
        {
            printf("Good job! You were right!\n");
            printf("%d is higher than %d\n", total2, total1);
        }

        else
        {
            printf("Sorry! %d is not lower than %d\n\n", total2, total1);
        }
    }

    else if (ans == 'S')
    {
        if (total2 == total1)
        {
            printf("Good job! You were right!\n");
            printf("%d is the same as %d\n", total2, total1);
        }

        else
        {
            printf("Sorry! %d is not lower than %d\n\n", total2, total1);
        }
    }

    return 0;
}

标签: c

解决方案


必须提供声明。[1] #include <stdlib.h>是这样做的正常方式

在标题中定义<stdlib.h>
void srand( unsigned seed );

也许在线编译器为您隐式包含它,或者它可能被另一个库间接包含。无论如何,您应该使用#include <stdlib.h>.


  1. 在 C99 或更高版本中,所有函数都是这种情况。(请注意,定义充当声明。)在 C99 之前,srand仍然需要一个,因为它的签名与默认的不匹配。

推荐阅读