#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) = %.5lf\n", 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( "%d\n", i );
printf("P(sum of the 3 dice is at least %d) = %.5lf\n\n", 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()
函数,因此它仅在每次运行代码时计算一个用户输入的值。