我正在尝试计算你需要购买彩票才能获胜的次数...但是我创建的这个程序一直在运行而且永远不会赢。我想不通为什么?我想这可能是因为兰特没有产生真正的随机数。
#include <iostream>
#include <sstream>
#include <ctime>
using namespace std;
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0;
int powerball = 0;
int pnum1 = 0, pnum2 = 0, pnum3 = 0, pnum4 = 0, pnum5 = 0;
int ppowerball = 0;
srand((unsigned int)time(0));
int max = 59;
int pmax = 35;
bool winner = false;
int count = 0;
while (winner == false) {
count++;
powerball = (rand()%pmax)+1;
num1 = (rand()%max)+1;
num2 = (rand()%max)+1;
while (num1 == num2)
num2 = (rand()%max)+1;
num3 = (rand()%max)+1;
while (num3 == num1 || num3 == num2)
num3 = (rand()%max)+1;
num4 = (rand()%max)+1;
while (num4 == num1 || num4 == num2 || num4 == num3)
num4 = (rand()%max)+1;
num5 =(rand()%max)+1;
while (num5 == num1 || num5 == num2 || num5 == num3 || num5 == num4)
num5 = (rand()%max)+1;
pnum1 = (rand()%max)+1;
pnum2 = (rand()%max)+1;
while (pnum2 == pnum1)
pnum2 = (rand()%max)+1;
pnum3 = (rand()%max)+1;
while (pnum3 == pnum1 || pnum3 == pnum2)
pnum3 = (rand()%max)+1;
pnum4 = (rand()%max)+1;
while (pnum4 == pnum1 || pnum4 == pnum2 || pnum4 == pnum3)
pnum4 = (rand()%max)+1;
pnum5 = (rand()%max)+1;
while (pnum5 == pnum1 || pnum5 == pnum2 || pnum5 == pnum3 || pnum5 == pnum4)
pnum5 = (rand()%max)+1;
ppowerball = (rand()%pmax)+1;
int myNumbers[] = {num1, num2, num3, num4, num5};
sort(myNumbers, myNumbers + sizeof myNumbers / sizeof myNumbers[0]);
int thereNumbers[] = {pnum1, pnum2, pnum3, pnum4, pnum5};
sort(thereNumbers, myNumbers + sizeof thereNumbers/ sizeof thereNumbers[0]);
if(myNumbers[0] == thereNumbers[0])
if(myNumbers[1] == thereNumbers[1])
if(myNumbers[2] == thereNumbers[2])
if(myNumbers[3] == thereNumbers[3])
if(myNumbers[4] == thereNumbers[4])
if(powerball == ppowerball){
winner = true;
cout << "Count: " << count << endl;
cout << num1 << "\t" << num2 << "\t" << num3 << "\t" << num4 << "\t" << num5 << "\tP: " << powerball << endl;
cout << pnum1 << "\t" << pnum2 << "\t" << pnum3 << "\t" << pnum4 << "\t" << pnum5 << "\tP: " << ppowerball << endl;
cout << endl;
}
if(count%1000000 == 0)
cout << count << endl;
}
cout << endl;
cout << "Count: " << count << endl;
cout << num1 << " " << num2 << " " << num3 << " " << num4 << " " << num5 << "P: " << powerball << endl;
return 0;
}
答案 0 :(得分:3)
我确实在你认为的程序中发现了一个错误。
您的sort()方法参数不正确。这导致您的数组被移位而没有正确排序。
请改为尝试:
int myNumbers[] = {num1, num2, num3, num4, num5};
sort(begin(myNumbers), end(myNumbers));
int thereNumbers[] = {pnum1, pnum2, pnum3, pnum4, pnum5};
sort(begin(thereNumbers), end(thereNumbers));
通过此更改,我能够让程序实际匹配两个数字并退出。
这里我在132,245,227次迭代中“赢了”当我运行你的代码时只有上面提到的更改:
Count: 132245227 32 57 24 4 23 P: 4