【问题标题】:program using the rand () function使用rand()函数的程序
【发布时间】:2015-04-29 09:14:23
【问题描述】:

我想编写一个简单的程序,其中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;

}

【问题讨论】:

  • 你的问题是什么?
  • 我认为game=(rand()%2) + 1 必须是game=(rand()%3) 因为你在第一个printf 中使用了0,1,2
  • @CoolGuy 对,将此添加到我的答案中。 :-)
  • 为什么需要循环?

标签: c random scanf modulo


【解决方案1】:

您的代码存在一些问题:

第 1 点:

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

应该是

    scanf("%d",&x);

第 2 点:

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

这个for循环实际上无用。它只迭代一个。要么使用更长的计数器,要么摆脱循环。

第 3 点:

最好为您的 PRNG 提供一个独特的种子。您可能希望在您的函数中使用 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() 一起使用时,请注意modulo bias issue


注意:

  1. main() 的推荐签名是int main(void)
  2. 始终初始化您的局部变量。很好的做法。

【讨论】:

    【解决方案2】:

    从你的 scanf() 中删除 \n

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

    scanf("%d",&x);
    

    并在game=(rand()%2) + 1; 之后放置一个分号(;) 它有效。

    这里不需要你的 for 循环。

    【讨论】:

      【解决方案3】:

      你没有问任何问题,但我猜是“为什么我的 rand() 函数不起作用?”

      你需要添加这些行

      #include <time.h>
      

      以及main函数开头的随机初始化:

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

      编辑:Sourav 说还有其他问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-30
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多