2

私はCで、2つのサイコロを振って合計を出力するプログラムを書いています。ゲームはとても簡単で、今は関数とループを組み込んでいるので、使用して何度か試行します。問題は、最初の試行後にスコアが変更されないことです。だから私は関数が機能していることを知っていますが、どういうわけかループは物事を捨てています。これが私のコードです:

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

3 に答える 3

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

一度呼び出しsrandて乱数ジェネレーターをシードしてから、呼び出しrandて乱数を取得します。

例を含む基本的な rand 関数のドキュメント

于 2012-09-19T19:51:50.313 に答える
0

srand() は乱数ジェネレーターのシードを初期化するために使用されます。rand() は実際に乱数を返す関数であるため、for ループの前に srand() を 1 回呼び出す必要があります。

于 2012-09-19T19:53:57.953 に答える
0

まず、1 から 6 の間の値を取得するには、次のようにする必要がありますsrand() % 6 + 1。モジュロ 5 は 0 から 4 の間の値を生成し、1 を追加すると 1 から 5 の間の数値が得られ、6 は決して出ません。
次に、2 つの num の合計を返したい場合は、2 番目の描画の値のみを返します。試す :

//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;
}
于 2012-09-19T20:00:45.863 に答える