为什么我的函数中的这个 for 循环只会运行一次,即使它应该运行多次?
Why does this for-loop in my function will only run once, even when it's supposed to run multiple times?
>有人可以向我解释为什么无论 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
等表达式时混合unsigned
和signed
类型时要非常小心。你知道如果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;
}
相关文章:
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 花括号使循环运行一次?
- 如何防止我的循环额外运行一次?
- 为什么循环只运行一次?
- 谷歌测试:如何为多个测试只运行一次夹具?
- CMAKE自定义目标仅运行一次
- Qt C++每秒运行一次代码
- 为什么我的函数中的这个 for 循环只会运行一次,即使它应该运行多次?
- 为什么我的fwrite命令只运行一次
- EXIT_SUCCESS和EXIT_FAILURE.它是在任何地方运行一次编译,还是在任何地方编写一次编译
- 是一个 for 循环,最终甚至不会运行一次,就像调用 if 语句以首先检查大小一样快
- C++,查找最低值,函数错误:循环最多运行一次(循环增量从未执行)
- 当循环应该只运行一次时,执行两次while循环(C++)
- C++循环最多运行一次
- 我的C++ Unity 插件在编辑器中运行一次,但不能运行两次
- C++:GetKeyState() 必须运行一次
- 如何使函数在程序的早期运行一次
- For 循环应该运行一次,但它没有运行
- 任务调度程序:从当前时刻开始,每小时运行一次任务
- 如何在没有外部标志的情况下只在循环中运行一次代码