#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int twoify(int num, int times)
{
num *= 2;
if (times > 0)
{
times--;
return twoify(num, times);
}
return num;
}
int main()
{
srand(time(NULL));
const int BET = 1;
const int TIMES = 100000;
const int CHANCE = 50;
int wins = 0;
int losses = 0;
in开发者_运维知识库t wstreak = 0;
int lstreak = 0;
int cwstreak = 0;
int clstreak = 0;
for (int i = 0; i < TIMES; i++)
{
int num = rand() % 100 + 1;
if (num <= CHANCE) // win?
{
wins++;
cwstreak++;
clstreak = 0;
if (cwstreak > wstreak)
wstreak = cwstreak;
}
else
{
losses++;
clstreak++;
cwstreak = 0;
if (clstreak > lstreak)
lstreak = clstreak;
}
}
cout << "Wins: " << wins << "\tLosses: " << losses << endl;
cout << "Win Streak: " << wstreak << "\tLoss Streak: " << lstreak << endl;
cout << "Worst lose bet: " << twoify(BET, lstreak) << endl;
system("PAUSE");
cout << endl << endl;
return main();
}
In particular, the twoify()
function seems noobis. This is a martingale bet pattern, and basically every loss you double your previous bet until you win.
First, avoid the useless recursion, turn it into iteration:
int twoify(int num, int times)
{
do {
num *= 2;
--times;
} while (times >= 0);
return num;
}
But, you can do better (if times > 0
is guaranteed, which would also simplify the version above by allowing you to use a while
instead of the do
/while
, but, anyway...):
int twoify(int num, int times)
{
return num << (times + 1);
}
The reason this works is that it's equivalent to multiplying num by 2 raised to the (times + 1)th power, which is what the recursive and iterative versions both do.
int twoify(int num, int times) {
return num << (times + 1); // num * 2**(times+1)
}
It's unclear why twoify is a recursive method. Maybe this was used during the class to introduce or illustrate recursion, but clearly this could be replaced by a function which multiplies num by 2^times. This can be expressed with the exponentiation mathematical operator of the C language or, as shown in other response, by doing a left shift operation, shifting by as many bits as the exponent (the "times" argument, here)
精彩评论