[英]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.