我給出的問題如下:C中的對接程序?
編寫一個程序來發現這個問題的答案的難題:「比方說,男人和女人是平等支付(從相同的均勻分佈)如果女性約會隨機嫁給第一個薪水更高的人,多少人口會結婚?「
我的問題是,它似乎%的已婚數字我得到是錯誤的。另一張海報asked this same question on the programmers exchange before,結婚的比例應該是〜68%。但是,我越來越接近75%(差異很多)。如果任何人都可以看一看,並讓我知道我出錯的地方,我會非常感激。
我意識到,看着程序員交換的另一個問題,即這不是解決問題的最有效方法。但是,我想在使用更有效的方法之前以這種方式解決問題。
我的代碼如下,問題的大部分是在測試功能「解決」:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_SIZE 100
#define MARRIED 1
#define SINGLE 0
#define MAX_SALARY 1000000
bool arrayContains(int* array, int val);
int test();
int main()
{
printf("Trial count: ");
int trials = GetInt();
int sum = 0;
for(int i = 0; i < trials; i++)
{
sum += test();
}
int average = (sum/trials) * 100;
printf("Approximately %d %% of the population will get married\n", average/ARRAY_SIZE);
}
int test()
{
srand(time(NULL));
int femArray[ARRAY_SIZE][2];
int maleArray[ARRAY_SIZE][2];
// load up random numbers
for (int i = 0; i < ARRAY_SIZE; i++)
{
femArray[i][0] = (rand() % MAX_SALARY);
femArray[i][1] = SINGLE;
maleArray[i][0] = (rand() % MAX_SALARY);
maleArray[i][1] = SINGLE;
}
srand(time(NULL));
int singleFemales = 0;
for (int k = 0; k < ARRAY_SIZE; k++)
{
int searches = 0; // count the unsuccessful matches
int checkedMates[ARRAY_SIZE] = {[0 ... ARRAY_SIZE - 1] = ARRAY_SIZE + 1};
while(true)
{
// ARRAY_SIZE - k is number of available people, subtract searches for people left
// checked all possible mates
if(((ARRAY_SIZE - k) - searches) == 0)
{
singleFemales++;
break;
}
int randMale = rand() % ARRAY_SIZE; // find a random male
while(arrayContains(checkedMates, randMale)) // ensure that the male was not checked earlier
{
randMale = rand() % ARRAY_SIZE;
}
checkedMates[searches] = randMale;
// male has a greater income and is single
if((femArray[k][0] < maleArray[randMale][0]) && (maleArray[randMale][1] == SINGLE))
{
femArray[k][1] = MARRIED;
maleArray[randMale][1] = MARRIED;
break;
}
else
{
searches++;
continue;
}
}
}
return ARRAY_SIZE - singleFemales;
}
bool arrayContains(int* array, int val)
{
for(int i = 0; i < ARRAY_SIZE; i++)
{
if (array[i] == val)
return true;
}
return false;
}
你每次做幾次試驗? –
您應該可以通過運行大量試驗和/或在每個試驗中測試更大的人羣來減少差異。 –
你也可以考慮*分配*均勻分配的工資,而不是從統一分配中隨機選擇工資;因爲薪水的順序並不重要,所以這些在無限人口限制上是等同的。 –