double lnchoose(int n, int m)
{
if (m > n)
{
return 0;
}
if (m < n/2.0)
{
m = n-m;
}
double s1 = 0;
for (int i=m+1; i<=n; i++)
{
s1 += log((double)i);
}
double s2 = 0;
int ub = n-m;
for (int i=2; i<=ub; i++)
{
s2 += log((double)i);
}
return s1-s2;
}
double choose(int n, int m)
{
if (m > n)
{
return 0;
}
return exp(lnchoose(n, m));
}
用之前调用math.h头文件,用的话直接把值赋给choose()这个函数即可,直接调用上面的函数,返回一个double数值,可追问
#include
void main(){
int n,k,sum=1;
printf("请输入组合数P=C(n,k)中的n、k:");
scanf("%d %d",&n,&k);
for (int i=k+1;i<=n;i++)
sum*=i;
for (i=1;i<=n-k;i++)
{
sum/=i;
}
printf("C(%d,%d)=%d\n",n,k,sum);
}
#include
int ZuHe(int n,int k)
{
int i = 1;
int temp1 = 1,temp2 =1;
if (n==k)
{
return 1;
}
else
{
for (i=1;i<=k;i++)
{
temp1 *= n-i+1;
temp2 *=i;
}
temp1 /=temp2;
return temp1;
}
}
void main()
{
int n,k,num;
printf("please input n and k:\n");
scanf("%d%d",&n,&k);
if (n
printf("wrong!");
}
num = ZuHe(n,k);
printf("%d\n",num);
}
/*
*求组合数C(n, k)
*@param n
*@param k
*@return 成功返回组合数,失败返回0
*/
unsigned f(unsigned n, unsigned k)
{
if (n < k || 0 == n)
{
return 0;
}
else
{
unsigned a = 1;
unsigned b = 1;
unsigned i = 0;
for (i = 0; i < n -k; i++)
{
a = a*(n - i);
}
for (i = 0; i < n - k; i++)
{
b = b*(i + 1);
}
return a/b;
}
}
//组合数P=C(n,k)=n*(n-1)*....*(n-k+1) / k!
int ZuHe(int n,int k)
{
int temp=1;
int f=1;
for(int i=0;i
f *= i+1;
temp *= (n-i) ;//
}
return (temp / f) ;
}