main.cpp
来自「经典的分油问题」· C++ 代码 · 共 68 行
CPP
68 行
#include <iostream>
using namespace std;
double single=200;
double useoil=300;
double tomile(double precost, double hive)
{
if (hive==0)
{
if (precost>=single)
{
return single+tomile(precost-single, single);
}
else
{
return precost;
}
}
else // hive>0
{
if (precost==0) // precost==0
{
return 0;
}
else // precost>0
{
int k;for(k=1;k*single<=hive;++k) ;
double iback=-1;
int bk;
for(;;++k)
{
double stagelength=(k*single-hive)/(2*k-1);
double newuse=stagelength*(2*k-1);
if (newuse>precost||stagelength*2>=single)
break;
double newiback=stagelength+tomile(precost-newuse, hive+newuse);
if (newiback>iback)
{
iback=newiback;
bk=k;
}
}
if (iback==-1)
{
for(k=2;(hive/k)+(precost*2/(2*k-1))>single;++k) ;
return precost/(2*k-1);
}
else
{
return iback;
}
} // end of precost>0
} // end of hive>0
}
int main()
{
cout<<"Use Oil: "<<useoil<<endl;
cout<<"Total mile: "<<tomile(useoil, 0)<<endl;
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?