求编程用c

来源:百度知道 编辑:UC知道 时间:2024/05/11 13:47:57
求1/2,1/3,1/4,1/5,……1/50中七个数和为1的程序。
我写的是
#include<stdio.h>
void main()
{
float x1,x2,x3,x4,x5,x6,x7;
for(x1=2;x1<25;x1++)
for(x2=x1+1;x2<50;x1++)
for(x3=x2+1;x3<50;x2++)
for(x4=x3+1;x4<50;x3++)
for(x5=x4+1;x5<50;x4++)
for(x6=x5+1;x6<50;x5++)
for(x7=x6+1;x7<50;x6++)
{
if(1.0/x1+1.0/x2+1.0/x3+1.0/x4+1.0/x5+1.0/x6+1.0/x7-1<=1e-6)
break;
}
printf("%f %f %f %f %f %f %f %f",x1,x2,x3,x4,x5,x6,x7);
}
但是结果不对
结果应该是
这些数是 1/2,1/12,……

在你程序基础上改了改,结果也好看了点。

#include<stdio.h>
void main()
{
float x1,x2,x3,x4,x5,x6,x7;
for(x1=2.0;x1<=50.;x1++)
for(x2=x1+1.0;x2<=50.;x2++)
for(x3=x2+1.0;x3<=50.;x3++)
for(x4=x3+1.0;x4<=50.;x4++)
for(x5=x4+1.0;x5<=50.;x5++)
for(x6=x5+1.0;x6<=50.;x6++)
for(x7=x6+1.0;x7<=50.;x7++)
{if(1.0/x1+1.0/x2+1.0/x3+1.0/x4+1.0/x5+1.0/x6+1.0/x7==1.0) printf("%d %d %d %d %d %d %d\n",(int)x1,(int)x2,(int)x3,(int)x4,(int)x5,(int)x6,(int)x7);
}

}

因为它是按float型运算的,结果对于这种运算是对的,而如果你是手工对分母分子分别运算,当然精度最高,不牵扯到小数,所以答案不一样。

..........显然是dfs

#include <stdio.h>

int stack[ 7 ];
double p[ 51 ][ 7 ];

void dfs( int t, double sum, int step )
{
if ( step < 7 )
{
int i;
for ( i = t + 1; i <= 44 + step; i++ )
{
stack[ step ] = i;
if ( sum + 1 / double( i ) > 1 && sum + 1 / double(