0

I am using using rand function to simulate a two dices , if the sum of two dices is prime the player wins but when ever compile it it gives a constant values of 236 , The output is always "Player wins236times" which shouldnt be the case if i am using rand() function

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>  
using namespace std;

int isprime(int num)
{
    int ans = 0;
    int i ;
    int root_x = sqrt(num);
    for(i = 2 ; i <=root_x ; i++ )
    {
        int check = num % i;
        if (check == 0 )
        {
            ans = ans+1;                
        }          
    }

    return ans;        
}

int main ()
{
   int counter = 0;
   int sum;
   int p_ans ;
   int j;
   int dice_1;
   int dice_2;
   for(j = 0 ; j< 500 ; j++)
   {
       dice_1 =  rand() % 6 + 1;
       dice_2 = rand() % 6 + 1;
       if (dice_1 == dice_2)
       {
           dice_2 = rand() % 6 + 1;
       }
       sum = dice_1 +dice_2;
       p_ans = isprime(sum);
       if(p_ans == 0)
       {
           counter = counter + 1 ;
       }              
   }

   cout<<"Player wins" <<counter<<"times\n" ;

   return 0;
}
jww
  • 97,681
  • 90
  • 411
  • 885
johnny
  • 171
  • 1
  • 12
  • 1
    [Read this: `std::srand`](http://en.cppreference.com/w/cpp/numeric/random/srand). – WhozCraig Dec 08 '14 at 00:09
  • 1
    `rand()` will produce the same sequence of numbers for a given seed, and in many cases thats a good thing, i.e. when you want to reproduce a sequence of numbers from a single number – dtech Dec 08 '14 at 00:09

0 Answers0