题目要求:
本题要求编写程序,根据公式Cnm=m!(n−m)!n!算出从n个不同元素中取出m个元素(m≤n)的组合数。
建议定义和调用函数fact(n)计算n!,其中n的类型是int,函数类型是double。
输入格式:
输入在一行中给出两个正整数m和n(m≤n),以空格分隔。
输出格式:
按照格式“result = 组合数计算结果”输出。题目保证结果在double类型范围内。
输入样例:
2 7
输出样例:
result = 21
正确代码:
#include<stdio.h>
double fact (int i);
int main(void){
int m,n;
double result=0;
scanf("%d %d",&m,&n);
while(m>n)
scanf("%d %d",&m,&n);
result=fact(n)/(fact(m)*fact(n-m));
printf("result = %.0f",result);
return 0;
}
double fact (int i){
double product=1;
int j;
for(j=1;j<=i;j++){
product=product*j;
}
return product;
}
错误代码如下:
#include<stdio.h>
double fact (int i);
int main(void){
unsigned int m,n;
double result=0;
scanf("%ud %ud",&m,&n);
while(m>n)
scanf("%ud %ud",&m,&n);
result=fact(n)/(fact(m)fact(n-m));
printf(“result = %.0f”,result);
return 0;
}
double fact (int i){
double product=1;
int j;
for(j=1;j<=i;j++){
product=productj;
}
return product;
}
问题不在于unsigned int上,而在于输入格式控制符上,对于无符号整型输入,应该直接用%u,正确代码如下
#include<stdio.h>
double fact (int i);
int main(void){
unsigned int m,n;
double result=0;
scanf("%u%u",&m,&n);//2 7
while(m>n)
scanf("%u%u",&m,&n);
result=fact(n)/(fact(m)*fact(n-m));
printf("result = %.0f",result);
return 0;
}
double fact (int i){
double product=1;
int j;
for(j=1;j<=i;j++){
product=product*j;
}
return product;
}
另外,输入多个变量的时候,控制符中最好不要加多余的字符,比如空格,直接紧挨着写即可
对于非格式控制符的字符,在输入的时候,应该原样输入,所以直接输入2 7 是不对的
for(j=1;j<=i;j++){
product=productj;
}
这段代码这个product * j你没有 *
然后不是unsigned int 和int的问题,因为int 和unsigned int在没出现负数的情况下传参是没有问题的。