程序忽略条件?

时间:2015-12-04 21:53:00

标签: c++ if-statement

在我的代码中,我试图阻止圆圈重叠,所以我将其指定为圈子中心之间距离的条件,但它似乎不能一直工作

你可以看到:

enter image description here

它可能是某种数值精度舍入问题吗?

以下是相关代码(如果需要,我可以发布整个代码):

const double win_size = 800;
const double L = 50e-9; //box size (m)
const double k = 1.38e-23; // Boltzmann constant = 1.38e-23 J/K
const double R = 1.6e-10*30;  //N2 radius = 1.6e-10 m 
const double m = 4.65e-26; //N2 mass = 4.65e-26 kg

struct parameters{
    double x;
    double y;
    double v_x;
    double v_y;
};

bool empty_space(double x, double y, struct parameters gas[], int N, int i){
    if (i == 0) return true;
    for (int i = 0; i<N; i++){
        if (pow(x-gas[i].x,2) + pow(y-gas[i].y,2) <= 4*R*R){
            cout << gas[i].x << " " << gas[i].y << endl;
            return false;
        }
    }
    return true;
}

void initialize(struct parameters gas[], int N, double T){    // Sets initial conditions (velocity depends on temperature)
    int tries = 0;
    double x, y;
    for (int i=0; i<N; i++){
        if (tries == 10000){
            cout << "Couldn't fit " << N << " molecules in the box, aborting simulation... " << endl;
            exit(1);
        }
        x = R + (L - 2*R)*rand()/RAND_MAX;
        y = R + (L - 2*R)*rand()/RAND_MAX;
        if (empty_space(x,y,gas,N,i)){
            gas[i].x = x;
            gas[i].y = y;
        }
        else {
            i--;
            tries++;
        }
        gas[i].v_x = sqrt(2*k*T/m)*(1-2.0*rand()/RAND_MAX);
        gas[i].v_y = (2*(rand()%2) - 1)*sqrt(2*k*T/m - pow(gas[i].v_x, 2));
    }
}

void draw(int window, struct parameters gas[], int N, int automatic){
    g2_pen(window,g2_ink(window,0.8,0.3,0.4));
    for (int i=0; i<N; i++){
        g2_circle(window,gas[i].x*win_size/L,gas[i].y*win_size/L,R*win_size/L);
    }
    g2_flush(window);
    usleep(10000);
    g2_pen(window,0);
    g2_filled_rectangle(window,0,0,win_size,win_size);
    if (!automatic) getchar();
}

1 个答案:

答案 0 :(得分:1)

第一个调试步骤是打印以某种方式发生冲突的圆圈的坐标,然后查看&#34;距离&#34;功能正在回归他们的中心。我猜这是一个舍入问题,但这似乎是你接下来需要做的事情。