gpt4 book ai didi

C:根据变量的值在for语句中使用不同的条件

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:08 24 4
gpt4 key购买 nike

所以我想实现一个 for 语句,其“长度”和条件取决于我给它的条目数变量的值。循环主要是读取文件。

例如,如果 number-of-entries 的命令行输入是一个正整数,我希望循环运行 number-of-entries 迭代或直到到达文件末尾;如果 number-of-entries 的输入是 -1,我希望循环运行到文件末尾。

有没有一种方法可以做到这一点而无需编写两次 for 循环,每个循环都嵌套在一个 if 语句中;有没有更简洁的方法?询问是因为 for 循环内的语句相同;唯一的区别是 for 参数中的条件。

这是我知道我能做的:

if ( number_of_entries > 0 ) {
for ( i = 0; i < number_of_entries; i++ ){
// set of for statements
// check to see if end of file is reached
// this case stops when i reaches number_of_entries or EOF
}
}

else if ( number_of_entries < 0 ) {
for ( i = 0; i > number_of_entries; i++ ){
// identical set of for statements
// check to see if end of file is reached
// this case stops at EOF because i will never reach number_of_entries
}
}

只是想知道我是否可以只保留一组 for 语句来做到这一点;因为它们在任何一种情况下都是相同的。

编辑:让我澄清一下第二种情况下的 i++:它仍然应该是 i++;第二个循环仅在到达文件末尾时结束。到那时我会继续增加。 number_of_entries 唯一可接受的输入是 -1 或任何正整数(程序中对此进行了检查)。

最佳答案

如何使用短路,以便仅在 number_of_entries 为正时测试 i:

for ( i = 0; number_of_entries < 0 || i < number_of_entries; i++ ){
// set of for statements
// check to see if end of file is reached
}

如果 number_of_entries 为负数,则 for 循环是一个无限循环(并且在检测结束时必须在内部使用 break文件)

因此,如果 number_of_entries 为正,则每次都是额外测试,但考虑到循环的内容(文件读取),性能不会受到太大影响。简洁与原始速度。

关于C:根据变量的值在for语句中使用不同的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016147/

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