如何在C中编写助手功能以从特定范围返回随机数并避免分割故障



我正在尝试编写一个程序,其中助手功能返回-999和999之间的随机整数,并将其返回以用于主函数。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rand(void) {
    int n;
    n = ((rand() % 1998 + 1) - 999);
    return n;
}

int main() {
    srand(time(NULL));     /* seed the random number generator */
    printf("%dn",rand());
    return 0;
}

然而,尽管在裸骨上进行调试的主要功能进行了许多不同的调整和简化,但我仍会得到分割的故障。

我想念什么?我究竟做错了什么?

-Wall编译为您提供线索:

$ gcc -Wall -o x x.c
x.c:6:16: warning: all paths through this function will call itself
      [-Winfinite-recursion]
int rand(void) {
               ^
1 warning generated.

您的rand()函数在呼叫自己,而不是库rand(),因为它们具有相同的名称。重命名您的功能。将其重命名为rand1在这里工作正常。

您想要哪个rand()?您的版本还是系统?似乎正在捡起您的递归,因此会吹堆。尝试重命名int myrand(void) {

最新更新