1111.cpp

来自「遗传算法求解函数y=x^2 在区间0-30的最大值」· C++ 代码 · 共 51 行

CPP
51
字号
#include <stdio.h> 
#include <math.h> 
#include <stdlib.h> 
#include <time.h> 

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] <= 31.002)) 
{ 
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); 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?