似乎无法让这个工作。这个想法是计算每次计数后头尾的百分比,在每次迭代后累积。除了我一直在 nan%进行计算。有谁看到我做错了什么?
void flipCoin(time_t seconds, int flipCount){
vector<int> flips;
float headCount = 0;
float tailCount = 0;
double headProbability = double((headCount/(headCount + tailCount))*100);
double tailProbability = double((tailCount/(headCount + tailCount))*100);
for (int i=0; i < flipCount; i++) {
int flip = rand() % (HEADS - TAILS + 1) + TAILS;
flips.push_back(flip);
if (flips[i] == 1) {
tailCount++;
cout << "Tail Percent: " << tailProbability << "%" << endl;
}else{
headCount++;
cout << "Head Percent: " << headProbability << "%" << endl;
}
}
}
答案 0 :(得分:2)
你想这样做
void flipCoin(time_t seconds, int flipCount){
vector<int> flips;
float headCount = 0;
float tailCount = 0;
double headProbability = 0;
double tailProbability = 0;
for (int i=0; i < flipCount; i++) {
int flip = rand() % (HEADS - TAILS + 1) + TAILS;
flips.push_back(flip);
if (flips[i] == 1) {
tailCount++;
tailProbability = double((tailCount/(headCount + tailCount))*100);
cout << "Tail Percent: " << tailProbability << "%" << endl;
}else{
headCount++;
headProbability = double((headCount/(headCount + tailCount))*100);
cout << "Head Percent: " << headProbability << "%" << endl;
}
}
}
此外,如果您只想打印百分比,则不需要tailProbability或headProbablity。您可以直接打印计算。
编辑:你也可以用i + 1替换headCount + tailCount。但如果稍后更改功能,则可能会出现问题。
答案 1 :(得分:1)
您的问题在于您只计算headProbability
和tailProbability
一次 - 当您计算它们时,它将评估为0 / 0
。
float headCount = 0;
float tailCount = 0;
// Both are 0, end up as 0/0
double headProbability = double((headCount/(headCount + tailCount))*100);
double tailProbability = double((tailCount/(headCount + tailCount))*100);
//Never recalculated in the loop
要解决此问题,只需将它们最初定义为0,然后在循环中重新计算它们。你似乎也不需要vector
,因为你只需要跟踪计数,而不是每次翻转的结果:
double headProbability = 0;
double tailProbability = 0;
for(int i = 0; i < flipCount; ++i) {
int flip = rand() % (HEAS - TAIL + 1) + TAILS; //This could be simplified
if(flip == 1) {
++tailCount;
//Recalculate tailProbability
} else {
//Etc...
}
}
答案 2 :(得分:0)
nan
表示不是数字。你得到它是因为你除以0。
你的代码计算概率只有一次,在任何翻转硬币之前。 您需要在循环中放置calculs,以便在每次迭代后重新计算概率。
void flipCoin(time_t seconds, int flipCount){
vector<int> flips;
float headCount = 0;
float tailCount = 0;
double headProbability;
double tailProbability;
for (int i=0; i < flipCount; i++) {
int flip = rand() % (HEADS - TAILS + 1) + TAILS;
flips.push_back(flip);
headProbability = double((headCount/(headCount + tailCount))*100);
tailProbability = double((tailCount/(headCount + tailCount))*100);
if (flips[i] == 1) {
tailCount++;
cout << "Tail Percent: " << tailProbability << "%" << endl;
}else{
headCount++;
cout << "Head Percent: " << headProbability << "%" << endl;
}
}
}