I cant count the number of times i get strange results from otherwise simple calculations. In this simple program I'm trying to calculate the chances of derangements as seen from this numberphile vid (https://www.youtube.com/watch?v=pbXg5EI5t4c), however near the end of my main I keep getting my total percentage
<< "total: " << static_cast<double>(matches / (matches + mismatch) * 100) << endl;
always resulting in a 0 regardless of what the values are. Thanks in advance and any help is appreciated.
my whole code:
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
void Fill(int[], int);
void Randomize(int[], int const);
int main()
{
int amount = 10, //size of array sample size
runs = 1, //how many test runs
matches = 0, //how many times each shuffle has 1 match
mismatch = 0; //how many times each shuffle has no matches
bool match;
unsigned seed = time(0);
srand(seed);
int cards[10];
Fill(cards, amount); //fills array to desired ammount
do
{
cout << "runs: ";
cin >> runs;
for(int i = runs; i > 0; i--)
{
Randomize(cards, ammount); //shuffle
for (int i = 0; i < ammount; i++)
{
if (cards[i] == i)
{
match = true;
break;
}
else match = 0;
}
if (match)
matches++;
else
mismatch++;
}
cout << "matches: " << matches << endl
<< "mismatches: " << mismatch << endl
<< "total: " << static_cast<double>(matches / (matches + mismatch) * 100) << endl;
}while (runs != 0);
return 0;
}
void Fill(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
arr[i] = i;
}
}
void Randomize(int a1[], int const size)
{
int a2[10];
int c = 0;
for(int i = 0; i < size; i++)
{
c = (rand() % (size - i));
a2[i] = a1[c];
a1[c] = a1[size - i - 1];
}
for(int i = 0; i < size; i++){a1[i] = a2[i];}
}