有没有办法 'reset' 一个函数变量?

Is there a way to 'reset' a functions variables?

我最近制作了一个函数,用于将数字数组与单个值进行比较,该值 returns 最接近数组中单个值的值。当你只使用它一次但如果我在代码的另一个实例中再次使用它时,这非常有效,它 returns 一个意外的值(通常是之前使用的前一个值)。这是我正在使用的函数:

double closestval (double num1, int amountofnums, double *comps){

double storagecomps[amountofnums];


for (int i = 0; i < amountofnums; i++){


storagecomps[i] = {comps[i]};
/* Storing the array of numbers for later as I will be changing them */
}



double smallval = 0.0001; /* tiny value used to increment/decrement
values in the array to the comparison variable.*/

int_fast64_t compi [amountofnums]; /* this variable keeps track of how many times it needs to decrement/increment the values in the array to approach the variable*/

for (int i = 0; i < amountofnums; i++){

compi[i] = 0;
}


for (int i = 0; i <= amountofnums; i++){

while (comps[i] > num1){

comps[i] -= smallval;
compi[i]++;

}
while (comps[i] < num1){


comps[i] += smallval;
compi[i]++;

}

double recholder[3] = {10000000, 0,};

// This area finds the 
for (int i = 0; i < amountofnums; i++){

if (compi[i] < recholder[0]){
recholder[0] = compi[i];
recholder [1] = i;
recholder[2] = storagecomps[i]; /* if the amount of iterations to approach the single variable is less than the previous record holder, it becomes the new one.
*/
}

}

return recholder[2];


}

我比较确定这是因为(以某种方式)函数中的变量没有被正确或根本没有被重新定义。如果你能告诉我哪里出错了,非常感谢!

问题不在于重置变量。问题是您正在修改传递给函数的参数。

要防止修改,您应该使用 const 关键字:

double closestval (double num1, int amountofnums, const double *comps){

然后修复编译器向您抛出的错误。

如果您确实想修改函数内部的 comps 但不影响函数外部的值,那么您应该使用std::vector 这样您就可以按值传递它们,编译器将复制它们:

double closestval (double num1, int amountofnums, std::vector<double> comps){

无论如何你真的应该这样做,因为在你成为专家之前你应该完全忘记 C-style 数组。