我正在比较三个不同的数组,在我的例子中,我的程序正在检查一个特定的圆与多少个其他圆相交。我的功能是这样做的:
void Intersection(int n, int A[], int B[], int C[])
{
ofstream out(rez);
for (int i = 0; i < n; i++)
{
times_condition_met=0;
for (int j = 0; j < n; j++)
{
if (Distance(X, Y, i, j) < (Radius[i] + Radius[j]))
{
times_condition_met++;
}
}
}
}
我在三个不同的数组中有圆心和半径的坐标。
X[] Y[] and R[]
这是必须满足的条件
if (Distance(X, Y, i, j) < (Radius[i] + Radius[j]))
times_condition_met++;
Distance
函数计算两点之间(圆心之间)的距离。
我在计算一个特定圆圈与多少个其他圆圈相交时遇到的问题是,当我的函数正在检查是否满足条件时,例如如果 Circle1
与 Circle2
times_condition_met++
相交,然后一段时间后循环检查 Circle2
是否与 Circle1< 相交
它再次执行 times_condition_met++
。那么我应该使用什么样的 if
以便 Circle1
与 Circle2
相交并且 Circle2
与 Circle1< 相交
会被计为条件只满足一次而不是两次?
最佳答案
我认为需要更新的是您的 for 循环。
尝试:
for (int i = 0; i < n-1; i++) // Update here
{
times_condition_met=0;
for (int j = i+1; j < n; j++) // Update here
通过这种方式,您只会比较两个特定的圈子一次。
在第一个循环中,圆圈 0 将与圆圈 1,2,..,n-1 进行比较
在第二个循环中,圆圈 1 将与圆圈 2,3,..,n-1 进行比较
在第三个循环中,圆圈 2 将与圆圈 3,4,..,n-1 进行比较
等等……
在最后一个循环中,第 n-2 圈将与第 n-1 圈进行比较
全部在一起 - 任何一对圆圈只检查一次。
要计算哪个圆与大多数圆相交,您可以这样做:
// Make a vector with n elements - all initialized to zero
std::vector hitcounter(n, 0);
for (int i = 0; i < n-1; i++)
{
times_condition_met=0;
for (int j = i+1; j < n; j++)
{
if (Distance(X, Y, i, j) < (Radius[i] + Radius[j]))
{
times_condition_met++;
// increment hit counter
hitcounter[i] = hitcounter[i] + 1;
hitcounter[j] = hitcounter[j] + 1;
}
}
}
int top = -1;
int topIndex = -1;
for (int i = 0; i < n; i++)
{
if (hitcounter[i] > top)
{
top = hitcounter[i];
topIndex = i;
}
}
if (top == -1)
{
cout << "No intersect found" << endl;
}
else
{
cout << "Most intersect found for circle " << topIndex << " Hits=" << top << endl;
}
关于c++ - 比较数组成员与嵌套循环,计算满足条件(if)的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072981/