骰子游戏坚持原始分数,但成功循环

时间:2012-09-19 19:50:10

标签: c function srand

我正在用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;
}

3 个答案:

答案 0 :(得分:1)

return (srand() % 5) + 1 , (srand() % 5) + 1;

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

Basic rand function documentation with an example

答案 1 :(得分:0)

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

答案 2 :(得分:0)

首先,要获得1到6之间的值,您必须执行srand() % 6 + 1之类的操作。 Modulo 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;
}