我的中断指令有问题;
确实,就我而言,我在下面的计算代码示例中进行了复制,我使用了两个嵌套的for循环和if循环。
我希望当open_bound变量= 0时,完全退出循环并因此显示时间t的值。执行后,我看到的是时间t = 0而不是3的显示,并且我很难理解为什么。你能开导我吗?
还有别的替代方法吗? (我不能使用goto,而且我在实际代码中并行化了这部分)
先感谢您
#include <iostream>
#include <vector>
using namespace std;
int main () {
int numtracers = 1000;
int save_t;
double t;
int open_bound = 0;
int tau = 5;
double int_step = 0.25;
for (int i = 0; i < numtracers; i++) {
// Variable to overwrite the successive positions of each particle
vector <double> coord(2);
coord[0] = 0.1;
coord[1] = 0.2;
int result_checkin;
for(t=0; t<tau-1; t+=int_step) {
save_t = t;
// Function to check if coordinates are inside the domain well defined
// result_checkin = check_out(coord);
if (t == tau-2) result_checkin = 1;
if (result_checkin == 1) { // Particle goes outside domain
if (open_bound == 0) {
break;
}
else {
coord[0]+=0.1;
coord[1]+=0.1;
}
}
else {
coord[0]+=0.1;
coord[1]+=0.1;
}
}
}
cout << save_t << endl;
return 0;
}
最佳答案
退出所需的所有循环的一种替代方法是使用bool标志来确定何时强制终止循环。当您按下open_bound=0
时,您可以先将标志设置为false,然后中断。
检查以下内容以了解我的意思:
bool go = true;
for (int i = 0; go && CONDITION1; i++)
for (int j = 0; go && CONDITION2; j++)
for (int k = 0; go && CONDITION3; k++)
....
if(open_bound==0){
go = false;
break;
}
您代码的有效版本为here
关于c++ - 还有别的替代方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58198138/