这里的学习者。
我制作了一个程序,可以生成一个随机数,该随机数接收输入供用户猜测该数字。 当我尝试以这种方式编写代码时:
#include<stdio.h>
int random(){
int num = random();
return num;
}
int main(){
int guess;
printf("I have a number, try guess it!");
scanf("%d", &guess);
if(guess == random()){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
我的编译器给出了一个Segment fault
错误。
但是当我像这样编写程序时,它可以编译和运行,没有错误。
#include<stdio.h>
int main(){
int guess;
int number = random();
printf("I have a number, try guess it! n");
scanf("%d", &guess);
if(guess == number){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
有人可以告诉我如何解决我上面提到的segment fault
错误吗?或者我怎样才能正确编写此代码?任何帮助不胜感激!<3
如果有人询问我的系统环境,我正在使用Windows 10和本网站的在线编译器:https://www.onlinegdb.com/online_c_compiler
在函数 random(( 中,你写了第一个代码,行
int num = random()
再次调用随机函数,而随机函数又再次调用随机,这将导致无限循环,这可能导致分割错误。
因此,将函数名称更改为其他名称,例如"random_number_generator"。
并且还要避免使用已经存在的关键字或内置函数名称的函数名称。
看看第二个:
#include<stdio.h>
int main(){
int guess;
int number = random();
printf("I have a number, try guess it! n");
scanf("%d", &guess);
if(guess == number){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
编译时,即使通过在线 gdb,您也应该看到:main.c:13:18: warning: implicit declaration of function ‘random’ [-Wimplicit-function-declaration]
.
造成这种情况的原因random
来自<stdlib.h>
。如果你有man
,你可以通过做man random
找到这个,否则你可以在这里检查:http://man7.org/linux/man-pages/man0/stdlib.h.0p.html。
在它下面你可以看到减速long random(void)
.因此,第二个有效的原因是您使用了stdlib.h
中的random
函数并隐式声明它,因为您没有显式包含该库(您应该这样做(。
第一个不起作用的原因是因为你正在使用递归,我假设你不是故意这样做的。如果你不熟悉编程,你可能不熟悉这个术语,但基本上这意味着你从函数本身中调用相同的函数。您没有停止条件,因此它会继续,直到它会导致堆栈溢出,从而导致 seg 错误。
当您执行以下操作时:
int random(){
int num = random(); // who do I call? stdlib or myself? it's me.
return num;
}
C 不知道外部random
与其中调用的random
不同。要更改此设置,您需要像这样重命名外部函数:
int my_random_func(){
int num = random(); // calls the stdlib random implicitly
return num;
}
这也是显式#include <stdlib.h>
的一个很好的理由,这样你就不会隐式使用你不想使用的函数。
#include <stdlib.h>
int my_random_func(){
int num = random(); // calls the stdlib random explicitly
return num;
}
当您显式使用所需的标头时,也可以获得更好的失败:
#include <stdlib.h> // explicitly state I want the stdlib header.
int random(){
int num = random(); // which do I call? There is my declaration and stdlib's...
return num;
}
这会导致以下错误消息:
main.c:12:5: error: conflicting types for ‘random’
int random(void) {
^~~~~~
In file included from main.c:10:0:
/usr/include/stdlib.h:321:17: note: previous declaration of ‘random’ was here
extern long int random (void) __THROW;
^~~~~~
希望这可以帮助您了解为什么您的标头不起作用,以及为什么您应该尽力明确包含您正在寻找的标头。