为什么我的函数中的这个 for 循环只会运行一次,即使它应该运行多次?

Why does this for-loop in my function will only run once, even when it's supposed to run multiple times?

本文关键字:运行 一次 函数 我的 循环 for 为什么      更新时间:2023-10-16

>有人可以向我解释为什么无论 n 是什么,这个 for 循环都只运行一次:

double CalcDist(unsigned int n, Point p, Point* s)
{
    double sd[n];
    for(int i = 0; i < n; i++)
    {
        sd[i] = s[i].Dist_To(p);
        return sd[i];
    }
}

提前感谢任何帮助。

return过早退出函数,并且位于for循环的主体中。

此外,在使用 i < n 等表达式时混合unsignedsigned类型时要非常小心。你知道如果n是0会发生什么吗?

如果您的目标是确定数组中一个点到每个点之间的距离,它是这样的:

double * CalcDist(unsigned int n, Point p, Point* pointsArray) {
    double * result = new double[n]; //Iso C++ forbids veriable length array
                                     //so don't use result[i] but this instead
    for (unsigned int i = 0; i < n; i++) { //set i as an unsigned int as n is one
        result[i] = pointsArray[i].Dist_To(p);
    }
    return result;
}