#include
#include
#include
#include
float f(float x)
{
return x * x;
}
void main()
{
float x[10];
float f1, f2;
int i, j;
float fmax;
int xfmax;
srand(time(NULL));
xfmax = 0;
x[0] = 15.0f;
f1 = f(x[0]);
f2 = f1 + 1.0f;
for (j = 0; fabs(f1 - f2) >= 0.0001f || j < 50; j++)
{
for (i = 0; i < 10; i++)
{
if (i != xfmax)
{
x[i] = -1;
while (!(x[i] >= 0 && x[i] <= 30))
{
x[i] = x[xfmax] + ((float)rand() / RAND_MAX * 2 - 1) * (15.0f / (j * 2 + 1));
}
}
}
xfmax = -1;
for (i = 0; i < 10; i++)
{
if (xfmax < 0 || fmax < f(x[i]))
{
fmax = f(x[i]);
xfmax = i;
}
}
f2 = f1;
f1 = fmax;
}
printf("f(%f) = %f\n", x[xfmax], fmax);
}
8
本文来源:https://www.2haoxitong.net/k/doc/dbc85bd376a20029bd642d4f.html
文档为doc格式