[英]How can I get back the value of iterations from this function to my main function?
I'm trying to return the iterations
back to main
from JacobiMethod
, but it still shows 0
even when I write return iterations;
我正在尝试将
iterations
从JacobiMethod
返回到main
,但即使我编写return iterations;
它仍然显示0
;
int JacobiMethod(double T[N][N], double c[N], double x[N], int iterations)
{
double x_new[N];
double x_prev[N];
double tmp=0;
while(magnitudeVectorDiff(x_new, x_prev) != 1)
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
tmp=tmp+T[i][j]*x[j];
}
x_new[i]=tmp+c[i];
tmp=0;
}
for(int i=0; i<N; i++)
{
x_prev[i]=x[i];
x[i]=x_new[i];
}
iterations++;
}
return iterations;
}
int main()
{
double A[N][N];
double v[N];
double x[N] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double LU[N][N];
double Dinv[N][N];
double T[N][N];
double c[N];
double x_new[N];
double x_prev[N];
int iterations=0;
read_data_from_file(A, v);
splitting_array(A, LU, Dinv);
T_and_c(LU, Dinv, v, T, c);
JacobiMethod(T, c, x, iterations);
iterations=JacobiMethod(T, c, x, iterations);
printArray(A);
printVectorV(v);
printf("Completed %d iterations (for tolerance = %lf).\n", iterations, TOL);
printf("%d\n", iterations);
printVector(x);
return 0;
}
Edit: I've added the main function above but I didn't include all the other functions of the program, as they are not that important for this question.编辑:我在上面添加了主要的 function 但我没有包括程序的所有其他功能,因为它们对于这个问题并不重要。
You need to store the return of your function in your variable for it to change:您需要将 function 的返回值存储在变量中以进行更改:
iterations = JacobiMethod(T, c, x, iterations);
And in your function, as explined in the comment, you can return iterations
and the return type of your function should be int
.在您的 function 中,如评论中所述,您可以
return iterations
,并且 function 的返回类型应为int
。
Note that the iterations
variables in the main and in your function JacobiMethod
are 2 different variables.请注意,main 和 function
JacobiMethod
中的iterations
变量是 2 个不同的变量。 They are both local variables available only in their respective functions.它们都是局部变量,只能在各自的函数中使用。 They just have the same name, but they are not the same variable.
它们只是具有相同的名称,但它们不是同一个变量。
When the variable iterations
changes in JacobiMethod
, the variable in the main
doesn't change.当
JacobiMethod
中的变量iterations
发生变化时, main
中的变量不会发生变化。
That's why you need to return the value from your function and assign the return of your function in the main.这就是为什么您需要从 function 中返回值并主要分配 function 的返回值的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.