#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
待办事项:实现下面名为 cum_prob 的函数。 此函数将整数 k 和长整数试验作为输入。 此函数返回双精度值。 在功能中,我们多次掷骰子 3 个骰子。投掷次数是试验。 我们计算 3 个骰子的结果加起来至少为 k 的次数。 然后我们用这个数字和试验来计算概率 3 个骰子的总和至少为 k。 最后,我们返回此概率。
double cum_prob(int k, long trials)
{
double count = 0;
double all_trials = 0;
double prob;
if (trials == 0)
return prob;
if (rand() % 18 + 3 == k)
{
(count ++);
(all_trials ++);
return cum_prob(k, -- trials);
}
else
{
(all_trials ++);
return cum_prob(k, -- trials);
}
prob = ((count / all_trials) * 100);
}
//Do not change the following code.
int main()
long n = 10000000;
int k;
printf("Enter k :");
scanf("%d", &k);
assert(k>= 3 && k<=18);
srand(12345);
printf("P(sum of the 3 dice is at least %d) = %.5lfn", k, cum_prob(k, n));
return 0;
}
以下建议的代码:
- 干净地编译
- 执行所需的功能
- 包含一个固定表(在代码中计算(
- 不使用递归或长循环
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
double cum_prob(int targetValue, long trials)
{
(void)trials;
int possibleResults[19] = {0};
// build table
for( int dice1 = 1; dice1 <=6; dice1++ )
{
for( int dice2 = 2; dice2 <= 6; dice2++ )
{
for( int dice3 = 1; dice3 <= 6; dice3++ )
{
possibleResults[ dice1+dice2+dice3 ]++;
}
}
}
// calculate total possible
double totalPossibilites = 0.0;
for( int index=0; index<=18; index++ )
{
totalPossibilites += (double)possibleResults[index];
}
int sumLessEqualTarget = 0;
for( int i = 0; i<targetValue; i++ )
{
sumLessEqualTarget += possibleResults[i];
}
return 100.0 - ((double)sumLessEqualTarget / totalPossibilites) *100.0;
}
//Do not change the following code
int main()
{
long n = 10000000;
//int k;
//printf("Enter k :");
//scanf("%d", &k);
//assert(k>= 3 && k<=18);
//srand(12345);
for( int i = 3; i<=18; i++ )
{
printf( "%dn", i );
printf("P(sum of the 3 dice is at least %d) = %.5lfnn", i, cum_prob(i, n));
}
return 0;
}
以下是有效输入范围的结果
3
P(sum of the 3 dice is at least 3) = 100.00000
4
P(sum of the 3 dice is at least 4) = 100.00000
5
P(sum of the 3 dice is at least 5) = 99.44444
6
P(sum of the 3 dice is at least 6) = 97.77778
7
P(sum of the 3 dice is at least 7) = 94.44444
8
P(sum of the 3 dice is at least 8) = 88.88889
9
P(sum of the 3 dice is at least 9) = 80.55556
10
P(sum of the 3 dice is at least 10) = 69.44444
11
Enter k P(sum of the 3 dice is at least 11) = 56.66667
12
P(sum of the 3 dice is at least 12) = 43.33333
13
P(sum of the 3 dice is at least 13) = 30.55556
14
P(sum of the 3 dice is at least 14) = 19.44444
15
P(sum of the 3 dice is at least 15) = 11.11111
16
P(sum of the 3 dice is at least 16) = 5.55556
17
P(sum of the 3 dice is at least 17) = 2.22222
18
P(sum of the 3 dice is at least 18) = 0.55556
您可以将原始源用于 main()
函数,因此它仅在每次运行代码时计算单个用户输入的值。