求根号n的值 模拟退火

#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
const int inf = 1e5 + 10;
int n;
double func(int x) {
    return fabs(x * x - n);
}
double T = 20000;
double dt = 0.993;
const double eps = 1e-14;
void SA() {
    double x = 0;
    double f = func(x);
    while (T > eps) {
        double dx = x + (rand() * 2 - RAND_MAX) * T;
        while (dx < 0)dx = x + (rand() * 2 - RAND_MAX) * T;
        double df = func(dx);
        if (df < f)x = dx, f = df;
        else if (exp((f - df) / T)*RAND_MAX > rand())x = dx, f = df;
        T *= dt;
    }
    cout << x;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    SA();
    return 0;
}


我是对比别人写的发现结果不对,也没找到哪里有问题

模拟退火是启发式算法,有一点点运气成分,多运行几次或者加大迭代次数,如果结果有改善应该就不是程序的问题了