任务是:
- 创建将产生f(x)=2x3-8x2+x+16的java语句
- 编写一个Java程序,在闭合区间(-1,3)内找到第1部分中函数的极值(高和低)
我不知道我到底做错了什么,但我得到了一个无限的数字9.09.09等等
import java.util.*;
import java.math.*;
public class Extrema
{
public static void main(String[] args)
{
double step = 0.00001;
double x = -1.0;
double xn = 3;
double highest = calc(x);
while (x <= xn)
{
double f = calc(x);
if (f > highest)
{
highest = f;
}
step++;
System.out.print(highest);
}
}
public static double calc(double x)
{
double f = 2*Math.pow(x, 1/3) - 8*Math.pow(x, 2) + x + 16;
return f;
}
}
在while循环的末尾(内部)添加x+=step
。
import java.util.*;
import java.math.*;
public class Extrema
{
public static void main(String[] args)
{
double step = 0.00001;
double x = -1.0;
double xn = 3;
double highest = calc(x);
while (x <= xn)
{
double f = calc(x);
if (f > highest)
{
highest = f;
}
x += step;
}
System.out.println(highest);
}
public static double calc(double x)
{
double f = 2*Math.pow(x, 3) - 8*Math.pow(x, 2) + x + 16;
return f;
}
}
这在我的系统上输出:16.03175629885453
。