gpt4 book ai didi

c - 为什么我在运行这段代码时会出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:00 25 4
gpt4 key购买 nike

我正在学习 switch 语句的使用以及 rand() 和 srand() 函数的使用,但是当我尝试运行从这本书中获得的这段代码时,我遇到了段错误我正在学习 C从。是什么导致了这种情况的发生?

#include <stdio.h>

int main(void)
{

int iRandomNum = 0;
srand(time());

iRandomNum = (rand() % 4) + 1;

printf("\nFortune Cookie - Chapter 3\n");

switch (iRandomNum) {

case 1:
printf("\nYou will meet a new friend today.\n");
break;
case 2:
printf("\nYou will enjoy a long and happy life.\n");
break;
case 3:
printf("\nOpportunity knocks softly. Can you hear it?\n");
break;
case 4:
printf("\nYou'll be financially rewarded for your good deeds.\n");
break;

} //end switch

printf("\nLucky lotto numbers: ");
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d\n", (rand() % 49) + 1);

} //end main function

最佳答案

这是因为 time() 需要一个参数,如果您打开所有警告,编译器会告诉您一些参数,例如 gcc -Wall -Wextra ...

不包括 time.h(意味着 time() 获得默认原型(prototype))和不带参数调用它的组合是您的特定问题。

使用高警告级别时发现的问题的完整列表是:

  • time()srand()rand()没有原型(prototype),需要#include stdlib.htime.h
  • time() 需要一个参数,例如 srand (time (0))
  • 您应该从 main 返回一些东西(在语言的非常最近的迭代中不是绝对必要的,但仍然是很好的做法)。

以下更改工作正常:

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

int main (void) {
int iRandomNum = 0;
srand (time (0));

iRandomNum = (rand() % 4) + 1;

printf("\nFortune Cookie - Chapter 3\n");

switch (iRandomNum) {
case 1:
printf("\nYou will meet a new friend today.\n");
break;
case 2:
printf("\nYou will enjoy a long and happy life.\n");
break;
case 3:
printf("\nOpportunity knocks softly. Can you hear it?\n");
break;
case 4:
printf("\nYou'll be financially rewarded for your good deeds.\n");
break;
} //end switch

printf("\nLucky lotto numbers: ");
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d ", (rand() % 49) + 1);
printf("%d\n", (rand() % 49) + 1);

return 0;
}

关于c - 为什么我在运行这段代码时会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com