问题1:编写函数int fac(int x)计算x!的值。在主函数中输入n和m的值,通过调用函数fac计算Cnm的值?
回答:
求组合C(m,n)不能简单的用阶乘,会溢出
把C(m,n)展开为
C(m, n)=C(m, n-1)*(m-n+1)/n
和
C(m,n)=C(m-1,n-1)+C(m-1,n)
能避开数据溢出
#include
using namespace std;
long int combination(int m, int n) {
if(n == 1) {
return m;
}
return combination(m, n - 1) * (m - n + 1) / n;
}
long int combination2(int m, int n) {
if(n == 0 || m == n)
return 1;
return combination2(m - 1, n - 1) + combination2(m - 1, n);
}
int main() {
int m, n;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
if(m < n) {
cout << "无效输入" << endl;
return 0;
}
cout << "组合:" << combination (m, n) << endl;
cout << "组合:" << combination2 (m, n) << endl;
return 1;
}
问题2:求标准差c语言程序看看哪里错了?
补充:
#include
#define MAXSIZE 100
main()
{
int i,n;
float value[MAXSIZE],d,s,ss,mean,v,st;
//d-deviation s-sum ss-sumsqr,st-standard variance
s=ss=n=0;
printf("input values:input 0 to end\n");
for(i=1;i
回答:
#include //补上
#include
#define MAXSIZE 100
int main() {
int i, n;
float value[MAXSIZE], d, s, ss, mean, v, st;
//d-deviation s-sum ss-sumsqr,st-standard variance
s = ss = n = 0;
printf("input values:input 0 to end\n");
for(i = 1; i < MAXSIZE; i++) {
scanf("%f", &value[i]);//漏写&
if(value[i] == 0)
break;
s += value[i];
n++;
}
mean = s / (float)n;
for(i = 1; i <= n; i++) {
d = value[i] - mean;
ss += d * d;
}
v = ss / (float)n;
st = sqrt(v);
printf("number of items:%d\n", n);
printf("mean:%f\n", mean);
printf("standard deviation:%f\n", st);
return 0;
}