gpt4 book ai didi

检查 for 语句中的条件

转载 作者:行者123 更新时间:2023-11-30 17:21:08 27 4
gpt4 key购买 nike

我编写了一个函数来检查某个数字是否存在于某个区间内。停止搜索的最佳方法是什么?这个:

for (i = a; i <= b; i++) {
fi = f(i);
if (fi == c) {
j = i;
break;
}
}

还是这个?

for (i = a; (i <= b) && (IsFound == 0); i++) {
fi = f(i);
if (fi == c) {
j = i;
IsFound = 1;
}
}

最佳答案

快速回答:break; 更好

为什么,一旦到达break,代码就会跳出循环。但在第二个选择中,您需要达到 for 循环条件检查状态

Quoting

The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.

代码说明中

选项一

for ( i = a; i <= b; i++ ){
fi = f ( i );
if ( fi == c ){
j = i;
break; // Simply exit from here , no more continuing
}
}

选项二

for ( i = a; (i <= b) && (IsFound == 0); i++ ) // Need to reach here for exit
{
fi = f ( i );
if ( fi == c ){
j = i;
IsFound = 1; // you set flag here but need to continue till for loop condition checking
}
}

关于检查 for 语句中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28383279/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com