我似乎无法在C
下的Ubuntu 12.04
中生成随机数。
我写了以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main (int argc,char* argv[])
{
int number;
clear();
number = rand() % 2; // want to get only 0 or 1
printf("%d",number);
getch();
return 0;
}
我将文件命名为“test_gcc.c”。
之后我用:
编译它$ sudo gcc -o test_gcc test_gcc.c
我收到以下消息:
/tmp/ccT0s12v.o: In function `main':
test_gcc.c:(.text+0xa): undefined reference to `stdscr'
test_gcc.c:(.text+0x12): undefined reference to `wclear'
test_gcc.c:(.text+0x44): undefined reference to `stdscr'
test_gcc.c:(.text+0x4c): undefined reference to `wgetch'
collect2: ld returned 1 exit status
有人可以告诉我,我做错了什么吗?
以及如何使用C
在Ubuntu 12.04
上gcc
生成随机数?
提前致谢!
答案 0 :(得分:5)
这与随机数无关。问题是您在没有curses
库的情况下进行链接。
您需要将-lncurses
添加到gcc
命令行:
$ gcc -o test_file test_file.c -lncurses
答案 1 :(得分:1)
您没有为随机数生成器播种。 &lt; - 不是错误的原因
在致电srand(time(0));
之前使用rand()
。
答案 2 :(得分:1)
在srand ( time(NULL) );
之前使用number = rand() % 2;
在每次运行可执行文件时获取不同的随机数。
错误:
删除clear()
并使用getchar()
代替getch()
,然后再使用getch()
应该工作得很好。
getchar()
用于支持非缓冲输入的编译器,但是在
gcc的情况是缓冲输入,所以请使用#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main (int argc,char* argv[])
{
int number;
srand(time(NULL));
number = rand() % 2; // want to get only 0 or 1
printf("%d",number);
getchar();
return 0;
}
。
<强>码强>
{{1}}
答案 3 :(得分:0)
尝试:
gcc -o test_gcc test_gcc.c -lncurses