C ++生日悖论程序[重复]
Posted
技术标签:
【中文标题】C ++生日悖论程序[重复]【英文标题】:C++ Birthday Paradox Program [duplicate] 【发布时间】:2015-09-01 19:12:40 【问题描述】:我正在尝试为我的 C++ 课程找出生日悖论程序。这是我到目前为止所拥有的,但它不起作用。我尝试在这里查看有关同一主题的其他问题,但我仍然很迷茫,因此将不胜感激。
//This program calculates the likelihood of any two people in groups of 2-50 people
//having their birthday on the same day, also known as the Birthday Paradox.
#include <iostream>
using namespace std;
int main()
int people, trial, count = 0, birthdays[50], numMatches, NUM_TRIALS = 5000;
double total;
//function call
sameBirthday(birthdays, people);
numMatches = 0;
for (people = 2; people <= 50; people++)
//Run trials to see if people have the same birthday
//Reset number of matches
numMatches = 0;
for (trial = 0; trial < NUM_TRIALS; trial++)
//Randomly generate up to "people" birthdays
for (int i = 0; i < people, i++)
birthdays[people] = (rand() % 365) + 1;
//Check to see if any two people have the same birthday
for (i = 1; i < people; i++)
//birthday one
for (int j = 0; j < i-1; j++)
//birthday two
for (int k = j +1; k < i; k++);
bool sameBirthday(int birthdays[], int people)
//if the two birthdays are the same, add one to the count
if (birthdays[j] == birthdays[k])
people++;
total = (numMatches / 5000.0);
cout << "For " << people << " people, the probability of two birthdays is about " << total << endl;
return 0;
【问题讨论】:
可能重复(选择一个)"*** c++ birthday paradox" 当您使用调试器时,哪些语句存在问题? 这是一期:birthdays[people] =
。变量people
在循环中没有变化,并且超出了数组的范围。您的意思是使用第一个 i
变量吗?
您有两个循环使用索引变量i
。虽然编译器不糊涂,你呢?也许您应该更改i
变量之一的名称。
你的k
循环没有做任何事情,去掉它或者给它一些内容。
【参考方案1】:
for (people = 2; people <= 50; people++)
//Run trials to see if people have the same birthday
//Reset number of matches
numMatches = 0;
for (trial = 0; trial < NUM_TRIALS; trial++)
//Randomly generate up to "people" birthdays
for (int i = 0; i < people, i++)
//here I use i instead of people so every time i put the new number in a different position
birthdays[i] = (rand() % 365) + 1;
//this loop check if some birthday is equal to the one just generated
for(int j = 0; j < i; j++)
if(birthday[j] == birthday[i])
//here do what u want to do when 2 people have the same birthday
尝试使用这个循环,这样,如果有 2 个人的生日相同,则检查从 2 到 50 的每个人数。
【讨论】:
以上是关于C ++生日悖论程序[重复]的主要内容,如果未能解决你的问题,请参考以下文章
c#,LINQ to Entities 无法识别方法'Int32 [重复]