[英]program using the rand () function
我想制作一个简单的程序,其中rand()
函数生成1,2,3中的随机数,并要求用户预测该数字。 如果用户正确预测了该数字,则他赢了,否则他就输了。 这是程序-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int game;
int i;
int x;
printf("enter the expected value(0,1,2)");
scanf("%d\n",&x);
for(i=0;i<1;i++){
game=(rand()%2) + 1
if(x==game){
printf("you win!");
}
else{
printf("you loose!");
}
} return 0;
}
从您的scanf()中删除\\n
scanf("%d\\n",&x);
至
scanf("%d",&x);
并在game=(rand()%2) + 1;
之后放置分号(;) game=(rand()%2) + 1;
有用。
这里不需要for循环。
您的代码存在一些问题:
第一点:
scanf("%d\n",&x);
应该
scanf("%d",&x);
第2点:
for(i=0;i<1;i++)
这个for循环实际上是没有用的 。 它仅迭代一个。 或者使用更长的计数器,或者摆脱循环。
第三点
最好为您的PRNG提供唯一的种子。 您可能要在srand()
中使用srand()
和time(NULL)
提供该种子。
第4点:
game=(rand()%2) + 1
应该
game = rand() % 3; // the ; maybe a typo in your case
^
|
%3 generates either of (0,1,2)
第5点:
当您将%
与rand()
,请注意模数偏差问题 。
注意:
main()
签名是int main(void)
。 您没有提出任何问题,但我想这是“为什么我的rand()函数不起作用?”
您需要添加这些行
#include <time.h>
在主函数的开头进行随机初始化:
srand(time(NULL));
哪个应该给:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int game;
int i;
int x;
printf("enter the expected value(0,1,2)");
scanf("%d",&x);
for(i=0;i<1;i++){
game=(rand()%2) + 1;
if(x==game){
printf("you win!");
}
else{
printf("you loose!");
}
} return 0;
}
编辑:苏拉夫说还有其他问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.