keep getting 0

the program generates 5 dice rolls and checks for three of a kind it loops through this a set number of times however the percent keeps coming out to be 0 and i can not figure out why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 #include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

/* function for getroll
void getRoll (){
cout << "Enter your 5 Yahtzee dice rolls: " ;
cin >> roll1,roll2,roll3,roll4,roll5;
}*/

// function for dice roll
int dieroll()
{

int ran=(rand()%6)+1;
return ran;
}

//function check three of a kind
bool threeOfAKind(int dA,int dB,int dC,int dD,int dE){
return (((dA==dB)+(dA==dC)+(dA==dD)+(dA==dE))==2||
        ((dB==dA)+(dB==dC)+(dB==dD)+(dB==dE))==2||
        ((dC==dA)+(dC==dB)+(dC==dD)+(dC==dE))==2);
}

int main()
{
// variables
int r1(0),r2(0),r3(0),r4(0),r5(0);
int three(0),total(0),counter(0);
double percent(1); 
const int trials=100;
// seed time
srand(time(0));

// output programs function
cout << "This program generates 5 random dice rolls and checks for 3 of a kind" << endl;
while (counter<=trials)
{
// generate 5 dice rolls
r1=dieroll();
r2=dieroll();
r3=dieroll();
r4=dieroll();
r5=dieroll();

three=threeOfAKind(r1,r2,r3,r4,r5);
 
if (three == 1)
{
	total=total++; 
}
counter=counter++; 
}
percent = (total/trials)*100;
cout << "the random rolls generated 3 of a kind " << percent << "% of the time." << endl; 

system("PAUSE");
    return 0;
}
This is a case of floating point division errors. Considering the total will always be less than the trials, and the result will therefore be less than one, because these are integers it gets truncated to 0. 0*100 is 0, so therefore you will always get 0 (unless it happened 100% of the time). Try multiplying total by 100 first, and then recalculate, or cast one to a floating point:
1
2
3
percent = (total * 100) / trials;
// OR
percent = (static_cast<float>(total) / trials) * 100;
Topic archived. No new replies allowed.