我正在学习使用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
Run Code Online (Sandbox Code Playgroud)
这是因为time()需要一个参数,编译器会告诉你是否打开了所有警告,例如gcc -Wall -Wextra ....
不包括time.h(意味着time()获得默认原型)和不带参数调用它的组合是您的具体问题.
使用higehr警告级别时发现的问题的完整列表如下:
time(),srand()并rand()没有原型,你需要#include两个stdlib.h和time.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;
}
Run Code Online (Sandbox Code Playgroud)