"错误:函数'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.nnn", 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.nnn", 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 %dn", total2, total1);
}
else
{
printf("Sorry! %d is not lower than %dnn", total2, total1);
}
}
else if (ans == 'H')
{
if (total2 > total1)
{
printf("Good job! You were right!n");
printf("%d is higher than %dn", total2, total1);
}
else
{
printf("Sorry! %d is not lower than %dnn", total2, total1);
}
}
else if (ans == 'S')
{
if (total2 == total1)
{
printf("Good job! You were right!n");
printf("%d is the same as %dn", total2, total1);
}
else
{
printf("Sorry! %d is not lower than %dnn", total2, total1);
}
}
return 0;
}

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

标头<stdlib.h>
void srand( unsigned seed );

可能是在线编译器隐式地为您包含了它,也可能是其他库间接包含了它。无论如何,您应该使用#include <stdlib.h>


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

最新更新