我正在研究一个函数,用于转置存储在 float
数组中的 NxN
矩阵。我的第一个实现似乎导致函数无限循环,我似乎无法弄清楚原因。原代码如下:
for(int i = 0; i < numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1; i++)
{
for(int j = i + 1; j < numColumns; j++)
{
//Swap [i,j]th element with [j,i]th element
}
}
但是函数永远不会返回。在我的逻辑中没有看到错误,我改写了表达式,现在有以下工作代码:
int middleRow = numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1;
for(int i = 0; i < middleRow; i++)
{
for(int j = i + 1; j < numColumns; j++)
{
//Swap [i,j]th element with [j,i]th element
}
}
谁能帮助解释为什么第一个版本不起作用,而看似等效的第二个版本却起作用?
最佳答案
根据 operator precedence表,<
优先于 ?:
.您需要使用 ()
明确要求执行所需的优先级。
改变
for(int i = 0; i < numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1; i++)
到
for(int i = 0; i < ( numRows % 2 == 0 ? numRows / 2 : numRows / 2 + 1) ; i++)
注意:请使用第二种方法。在可读性、维护和理解方面好多了。
关于c - For 循环中的三元运算符导致无限迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858331/