简体   繁体   English

程序使用rand()函数

[英]program using the rand () function

I want to make a simple program in which the rand() function generates a random number out of 1,2,3 and the user is asked to predict the number. 我想制作一个简单的程序,其中rand()函数生成1,2,3中的随机数,并要求用户预测该数字。 if the user predicts the number correctly then he wins otherwise he looses. 如果用户正确预测了该数字,则他赢了,否则他就输了。 Here's the program- 这是程序-

#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;

}

Remove \\n from your scanf() 从您的scanf()中删除\\n

scanf("%d\\n",&x); to

scanf("%d",&x);

and place a semicolon(;) after game=(rand()%2) + 1; 并在game=(rand()%2) + 1;之后放置分号(;) game=(rand()%2) + 1; it works. 有用。

Your for loop is not required here. 这里不需要for循环。

Some issues with your code: 您的代码存在一些问题:

Point 1: 第一点:

    scanf("%d\n",&x);

should be 应该

    scanf("%d",&x);

Point 2: 第2点:

for(i=0;i<1;i++)

this for loop is practically useless . 这个for循环实际上是没有用的 It only iterates one. 它仅迭代一个。 either use a longer counter, or get rid of the loop. 或者使用更长的计数器,或者摆脱循环。

Point 3: 第三点

It's better to provide a unique seed to your PRNG. 最好为您的PRNG提供唯一的种子。 You may want to use srand() and time(NULL) in your function to provide that seed. 您可能要在srand()中使用srand()time(NULL)提供该种子。

Point 4: 第4点:

game=(rand()%2) + 1

should be 应该

game = rand() % 3; // the ; maybe a typo in your case
                ^
                |
          %3 generates either of (0,1,2)

Point 5: 第5点:

When you use % with rand() , be aware of modulo bias issue . 当您将%rand() ,请注意模数偏差问题


Note: 注意:

  1. The recommended signature of main() is int main(void) . 推荐的main()签名是int main(void)
  2. Always initialize your local variables. 始终初始化局部变量。 Good practice. 好的做法。

You didn't ask any question but I guess it is "Why my rand() function doesn't work?" 您没有提出任何问题,但我想这是“为什么我的rand()函数不起作用?”

You need to add these lines 您需要添加这些行

#include <time.h>

and the random initialization at the beginning of the main function: 在主函数的开头进行随机初始化:

srand(time(NULL));

Which should give: 哪个应该给:

#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;

}

Edit: there are other problems as Sourav said 编辑:苏拉夫说还有其他问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM