C语言 如何阻止变量在第一次进入循环后改变值

sgtfey8w  于 2022-12-22  发布在  其他
关注(0)|答案(3)|浏览(136)

我试图让一个变量只在循环的第一次迭代中改变,除非另一个条件使它需要一个不同的值。

for (int i = 0; i < numOfIterations; i++){
   if (this happens){
   value = i;  //trying to save that particular position
   }

//Now the problem is: the value will change in the next iteration.

我如何停止它而不停止循环?

iovurdzv

iovurdzv1#

#include <stdbool.h>

bool setValue = true;  

for (int i = 0; i < numOfIterations; i++){
   if (this happens && setValue){
       value = i;  //trying to save that particular position
       setValue = false; // Now that setValue is false
                         // variable "value" will not be set again,
                         // even if "this happens" is true
   } // End of if
} // End of For-loop
hm2xizp9

hm2xizp92#

最简单的方法是

for (int i = 0; i < numOfIterations; i++){
   if (this happens && i == 0){
   value = i;
   }
}
eagi6jfj

eagi6jfj3#

for (int i = 0; i < numOfIterations; i++){
   if (this happens && i == 0) {  //that means if i is equal to 0 and your condition is true, code will be executed
       value = i;  //trying to save that particular position
   }
}

相关问题