给定求组合数公式为:C(n,m)=m!/n!(m-n)!,编一程序,输入m和n的值 ,求C(n,m)的值

要求主函数调用以下函数求组合数:
int Fabricate(int m,int n); //返回C(n,m)的值
Fabricate函数内又许调用Multi函数:
int multi(int m,int n); //返回m*m-1*...*n
最新回答
浮华沧桑

2024-06-09 05:54:02

#include<stdio.h>
int Fabricate(int m,int n);
int multi(int m,int n);
void main()
{
int m,n,answer;
printf("输入m(按q退出):");
while(scanf("%d",&m))
{
printf("输入n:");
scanf("%d",&n);
if(n!=0&&m!=0)//判断m,n是否为0
{
if(m>n) //自动将大数设置为m,小数设置为n
printf( "%d\n", Fabricate(m,n));
else
printf( "%d\n", Fabricate(n,m));
printf("输入m(按q退出):");
}
else
printf("错误!重新输入,输入m:");

}

}
int Fabricate(int m,int n)
{
int sum_m=1,sum_n=1,sum_mn,sum;
int i=m,j=n;
for(int i=m;i>0;i--)//求m的阶乘
sum_m*=i;
for(int j=0;j>0;j--)//求n的阶乘
sum_n*=j;
sum_mn=multi(m,n);
return (sum_m/sum_n)*sum_mn;

}
int multi(int m,int n)
{
int sum=1;
int k=m-n;
while(k>0)
sum*=k--;
return sum;
}
薄荷绿℡

2024-06-09 09:21:56

#include<iostream>
using namespace std;
int main()
{
int m,n;
int Fabricate(int m, int n);
while(cin>>m>>n)
cout<<Fabricate(m,n)<<endl;
return 0;
}

int Fabricate(int m, int n)
{
int Multi(int m, int n);
cout<<Multi(m,n)<<endl;
if(n>m-n) return Multi(m,n+1)/Multi(m-n,1);
else return Multi(m,m-n+1)/Multi(n,1);
}
int Multi(int m,int n)
{
if(m<n) return 1;
if(m==n) return n;
return m*Multi(m-1,n);
}