5: 求组合数

5: 求组合数

本题要求编写程序,根据公式C ​n ​m ​​ = ​m!(n−m)! ​ ​n! ​​
算出从n个不同元素中取出m个元素(m≤n)的组合数。

建议定义和调用函数fact(n)计算n!,其中n的类型是int,函数类型是double。

输入格式:
输入在一行中给出两个正整数m和n(m≤n),以空格分隔。

输出格式:
按照格式“result = 组合数计算结果”输出。题目保证结果在double类型范围内。

输入样例:
2 7

输出样例:
result = 21

作者: 颜晖
单位: 浙江大学城市学院
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
在这里插入图片描述

#include <stdio.h>
double fact(int n);
int main()
{
    /*
    int i;
    for(i=1; i<32; i++)
    {
       printf("%d:%f\n", i, fact(i));
    }
    */
    // /*
    int m, n;
    scanf("%d%d", &m, &n);
    printf("result = %d\n", (int)(fact(n)/fact(m)/fact(n-m)) );
    // */
    return 0;
}
double fact(int n)
{
    double multiple=1.0; //此处若用int类型则范围不够
    while(n)
    {
        multiple *= n;
        n--;
    }
    return multiple;
}

在这里插入图片描述

#include <stdio.h>
double f (int n)
{
    	double s = 1;
        for(int i = 1;i < n + 1;i ++)
        {
        s *= i;
		}
        return s;
}
int main()
{
    int m,n;
    scanf("%d%d",&m,&n);
    int c = n - m;
    printf("result = %.0f",f(n)/(f(m)*f(c)));
}

在这里插入图片描述

#include <stdio.h>
double fact(int n);
int main()
{
	int m,n;
	if(scanf("%d %d",&m,&n));
	double result;
	result=fact(n)/(fact(m)*fact(n-m));
	printf("result = %.0lf",result);
	return 0;
}
double fact(int n)
{
	double fact=1;
	for(int i=2;i<=n;i++)
	{
		fact*=i;
	} 
	return fact;
}

在这里插入图片描述

#include <stdio.h>
double fa(double n);
int main()
{
    double n, a, m; 
    scanf("%lf%lf",&m,&n);
    a=fa(n)/(fa(n-m)*fa(m));
    printf("result = %.0lf",a);
    return 0;
}

double fa(double n)
{
    double i, fact=1;
    
    for(i=1;i<=n;i++)
        fact=fact*i;

    return fact;
}

在这里插入图片描述

#include<stdio.h>
double fact (int n);
int main (void)
{       
    int i, n, m;
 double result;
 scanf("%d%d", &m, &n);
 result=1;
 for(i=0; i<=n; i++)
 {
     result=fact(n)/(fact(m)*fact(n-m)); 
 }
 printf("result = %.0f", result);
 return 0;
}
double fact (int n)
{         
      int i;
      double product;
      product=1; 
      for(i=1; i<=n; i++)
      { 
      product=product*i;
     } 
       return product;
}

在这里插入图片描述

#include <stdio.h>
int main () {
    double factorial( int number);
    int n,m;
    double  result; 
    scanf ("%d%d",&m,&n);
   // printf ("n!=%d\tm!=%d\t(n-m)!=%d\n",factorial(n),factorial(m),factorial(n-m));
    result =  factorial(n)/factorial(m)/factorial(n-m);
    if (m)                       
        printf("result = %.0f",result);
    else
        printf("result = 0");
    return 0 ;
}
    double factorial( int number)
    {     
        double result=1.0;
        while(number--){
            result *= number + 1 ;
        }
        return result ;
    }

在这里插入图片描述

发布了15 篇原创文章 · 获赞 1 · 访问量 340

猜你喜欢

转载自blog.csdn.net/weixin_46640830/article/details/105570035
今日推荐