【问题标题】:Dice game sticking with original score but looping successfully骰子游戏坚持原始分数但循环成功
【发布时间】:2012-09-19 19:50:10
【问题描述】:

我正在用 C 语言编写一个程序,它将掷两个骰子并输出总和。 游戏很简单,现在我正在合并一个函数和循环,以便使用将进行多次尝试。问题是第一次尝试后分数永远不会改变。所以我知道该功能正在工作,但不知何故循环正在抛出一些东西。这是我的代码:

#include<stdio.h>


//Function prototype
int RollScore(int , int);

main()
{
  int LoopCount;
  LoopCount = 0;

  for(LoopCount = 0; LoopCount < 11; LoopCount ++)
  {


 //Declare Variables
  int DieOne,DieTwo,DiceScore;

  //  One and Two will be hidden only Score will be output  
  DieOne = 0;
  DieTwo = 0;
  DiceScore = 0;


  printf("\n\n\tTo win you need a score of 7 or 11.");
  printf("\n\n\tPress a key to Roll the Dice!");

  //Trigger Random number generator and remove previous text    
  getch();
  system("cls");

  DiceScore = RollScore(DieOne , DieTwo);

  //Create Condition to either show user a win/lose output
  if (DiceScore == 7 || DiceScore == 11)
    {
                printf("\n\n\n\t\tYou Rolled a score of %d" , DiceScore);
                printf("\n\n\n\t\tCongratulation! You win!");

                LoopCount = 11;
    }//end if
     else
         {
                  printf("\n\n\n\t\tYou Rolled a score of %d" , DiceScore);
                  printf("\n\n\n\t\tSorry you have lost! Thanks for playing!");                 
                  printf("\n\n\t %d Attempt!" , LoopCount);
         }//end else

  //Prevent the IDE from closing program upon termination
  getch();
  system("cls");

  }//End For




}

//Function definition
int RollScore (int Dieone , int Dietwo)
{
return (srand() % 5) + 1 , (srand() % 5) + 1;
}

【问题讨论】:

  • 初学者。做了一些努力。使用代码格式和英语足够好。 +1 鼓励他。

标签: c function srand


【解决方案1】:
return (srand() % 5) + 1 , (srand() % 5) + 1;

调用srand 一次以播种随机数生成器,然后调用rand 以获取随机数。

Basic rand function documentation with an example.

【讨论】:

  • 所以看起来应该是:return (srand() % 5) + 1 , (rand() % 5) + 1;??
  • 一次,ouah 意味着在整个程序中(开始时)一次,而不是每次调用rand
  • @Ev00 不,你不应该使用逗号,那里的逗号意味着第一个表达式被计算并且它的值被忽略,那么你应该使用逗号之后的表达式的值返回+ 那里。和% 6 而不是% 5
【解决方案2】:

srand() 用于初始化随机数生成器的种子,rand() 是实际返回随机数的函数,因此您需要在 for 循环之前调用 srand() 一次,

【讨论】:

    【解决方案3】:

    首先,要获得介于 1 和 6 之间的值,您必须执行 srand() % 6 + 1 之类的操作。模 5 产生一个介于 0 和 4 之间的值,加 1 你会得到一个介于 1 和 5 之间的数字,6 永远不会出现。
    第二次你想返回两个num之和,你只返回第二次平局的值。试试看:

    //Function definition
    int RollScore (int Dieone , int Dietwo)
    {
      return (srand() % 6) + 1 + (srand() % 6) + 1;
    }
    

    如果您想要抽签结果,请不要忘记使用指针...

    //Function definition
    int RollScore (int *Dieone , int *Dietwo)
    {
      *Dieone = srand() % 6 + 1;
      *Dietwo = srand() % 6 + 1;
      return *Dieone + *Dietwo;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 2014-02-28
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多