gpt4 book ai didi

java - 在 Java 中转换时在 C 代码中出现指针和 if 语句错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:03 25 4
gpt4 key购买 nike

我正在尝试将 C 代码转换为 java,它是 Newton Raphson 算法的实现。一切顺利,但 C 代码中使用的指针存在问题,我已在 Java 中删除了它们。 C代码部分是:

 x = newton(x_0, error, max_iters, &iters, &converged); //Call to a function (newton)

if (converged) {

printf("Newton algorithm converged after %d steps.\n", iters);

printf("The approximate solution is %19.16e\n", x);
printf("f(%19.16e) = %19.16e\n", x, f(x));
} else
{

printf("Newton algorithm didn't converge after %d steps.\n",
iters);

printf("The final estimate was %19.16e\n", x);
printf("f(%19.16e) = %19.16e\n", x, f(x));
}

函数定义是这样的:

double newton(double x_0, double error, int max_iters, 
int* iters_p, int* converged_p)

现在的问题是,两个指针变量的值每次都为零。此外,if(converged) 显示了不兼容类型的错误消息。需要 boolean 值,找到 int。下面是 java 代码,请帮助解决这个问题。

 //Member Functions///////
public
double function( double x)
{
return x*x - 2;
}

double F_Deriv( double x )
{
return 2.0*x;
}


double newton(double x_0, double error, int max_iters,int iters, int converged)
{
double x = x_0;
double x_prev;
int iter = 0;

do {
iter++;
x_prev = x;
x = x_prev - function(x_prev)/F_Deriv(x_prev);
}
while (Math.abs(x - x_prev) > error && iter < max_iters);

if (Math.abs(x - x_prev) <= error)
converged = 1;
else
converged = 0;
iters = iter;

return x;
}


/////Main Function///////
public static void main(String[] args) {

Newton_Raphson obj=new Newton_Raphson();

Scanner input=new Scanner(System.in);


double x_0; /* Initial guess */
double x; /* Approximate solution */
double error; /* Maximum error */
int max_iters; /* Maximum number of iterations */
int iters; /* Actual number of iterations */
int converged; /* Whether iteration converged */

System.out.println( "Enter Initial Solution: " );
x_0=input.nextDouble();

System.out.println( "Enter Error: " );
error=input.nextDouble();


System.out.println( "Enter Maximum Iterations: " );
max_iters=input.nextInt();

x = obj.newton(x_0, error, max_iters, iters, converged);

if(converged)
{
System.out.println("Newton algorithm converged after "+ iters +" steps.");
System.out.println("The approximate solution is "+ x);

}

else
{
System.out.println("Newton algorithm didn't converge after " + iters + " steps.");
System.out.println("The final estimate was " + x);

}

}

最佳答案

Java 按值传递参数,所以

if (Math.abs(x - x_prev) <= error)
converged = 1;
else
converged = 0;
iters = iter;

不会更改调用者传递的参数。这些更改永远不会离开被调用的函数。

模仿输出参数的最简单方法,resp。 C中传递指针,就是传递一个单长数组,

double newton(double x_0, double error, int[] max_iters,int iters, boolean[] converged)

并设置(和查询)iters[0] resp。 收敛[0]

关于java - 在 Java 中转换时在 C 代码中出现指针和 if 语句错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10412585/

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