我正在学习C并且发现rand()非常奇怪:
我有以下游戏: 我已经玩了几次游戏,正确答案是47附近。
例如:
#include<stdio.h>
#include<stdlib.h>
void main()
{int n,l,c,tries;
char yn;
first:
n=0,c=0,l=0,tries=0;
do{
printf(" 1: Easy\n 2:Medium\n 3:hard\n");
scanf("%d",&l);
}while(l<1 || l>3);
switch(l)
{
case 1:
n = rand % 100 +1;
printf("I picked a number between 1 and 100\n");
break;
case 2:
n = rand()%500 + 1;
printf("I picked a number between 1 and 500\n");
break;
case 3:
n = rand()%1000 + 1;
printf("I picked a number between 1 and 1000\n");
break;
}
do
{
tries++;
printf("Enter your guess: \t");
scanf("%d",&c);
if(c == n)
printf("You Won\n number of gusses= %d\n", tries);
else
{
if(c > n)
printf("High\n");
else
printf("Low\n");
}
}while(c !=n);
printf("Try Again \?(Y/N)\n");
scanf(" %c",&yn);
if(yn == 'Y' || yn == 'y')
goto first;
}
答案 0 :(得分:3)
如果您重新启动电脑,您会发现结果会有所不同 随机并不像你期望的那样聪明,而且,说实话,并不是随意的! (:
顺便说一下,要为随机的alghoritm提供不同的种子,你只需要打电话一次:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
srand(time(0));
改善您的代码:
int randN = 100;
switch (l) {
case 1:
break;
case 2:
randN = 500;
break;
case 3:
randN= 1000;
break;
default:
randN = rand() % 1000 + 1;
break;
}
n = rand() % randN + 1;
printf("I picked a number between 1 and %i.\n", randN);
答案 1 :(得分:1)
使用srand然后使用rand,即
int main()
{
srand(time(0)); // use current time as seed for random generator
int random_variable = rand();
printf("Random Value= %d",random_variable);
return 0;
}