#include <iostream>
#include <math.h>
usingnamespace std;
int berechneWK();
int main()
{
cout<<berechneWK()<<endl;
}
int berechneWK()
{
int n,k,p,n2,k2,n3,k3,gemischt;
cin>>n;
cin>>k;
cin>>p;
long nfakultaet=n,kfakultaet=k,gemischtefakultaet=n-k;
n2=n;
k2=k;
k3=k;
n3=n;
gemischt=n2-k2;
while(n>0)
{
nfakultaet*=n-1;
n--;
}
while(k>0)
{
kfakultaet*=k-1;
k--;
}
while(gemischt>0)
{
gemischtefakultaet*=gemischt-1;
gemischt--;
}
return ((nfakultaet)/(kfakultaet*gemischtefakultaet)) * pow(p,k3) * pow(1-p,n3-k3);
}
As I run this, I receive the error floating point exception (core dumped). I think the problem are the loops but I am not sure. Any idea how to solve that or tipp on how to calculate the probability more easy?
First, you can't use int to calculate factorials. the largest factorial you can compute is 12!. You will probably need to find a way to simplify away factors from the multiplication.
Second, the way you're computing factorials is incorrect anyway. Look at what you're doing. The last value of n on lines 28-32 is n == 1, and you're multiplying nfakultaet by n - 1. The result is just zero. This is the immediate cause of the exception, since the divisor in (nfakultaet)/(kfakultaet*gemischtefakultaet) is zero.
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int n, k;
double p;
cout << "Input the number of trials (n): "; cin >> n;
cout << "Input the probability of success on each trial (p): "; cin >> p;
cout << "Input the number of successes (k): "; cin >> k;
double log_answer = k * log( p ) + ( n - k ) * log( 1.0 - p );
for ( int nn = n, kk = k; kk; nn--, kk-- ) log_answer += log( (double)nn / kk );
cout << "Probability is " << exp( log_answer );
}
Input the number of trials (n): 100
Input the probability of success on each trial (p): 0.3
Input the number of successes (k): 35
Probability is 0.0467797
You can compute large, exact values of the combinations function nCk by alternating the multiplication and division. The beauty is that each division results in an integer result. Here's an example, with debug code to show what it does: