我的java代码需要帮助。我想要完成的是计算多项式上每一步的大小:double s = (b-a)/nsteps;
要创建的多项式的输入是度,系数,x
的起始值,x
的停止值以及步数。每当我尝试运行测试时,0
和x
的输出为y
,我不确定我的代码中缺少什么。
以下是我应该如何工作的运行测试,但x
和y
的结果是0
:
Enter degree:2
Enter coefficient 2:1
Enter coefficient 1:0
Enter coefficient 0:0
f(x) = 1.0x^2 + .0x^1 + 0.0
Enter initial x:0
Enter final x:10
Enter number of steps:20
x = 0.0; f(x) = 0.0
x = 0.5; f(x) = 0.25
x = 1.0; f(x) = 1.0
x = 1.5; f(x) = 2.25
x = 2.0; f(x) = 4.0
x = 2.5; f(x) = 6.25
x = 3.0; f(x) = 9.0
x = 3.5; f(x) = 12.25
x = 4.0; f(x) = 16.0
x = 4.5; f(x) = 20.25
x = 5.0; f(x) = 25.0
x = 5.5; f(x) = 30.25
x = 6.0; f(x) = 36.0
x = 6.5; f(x) = 42.25
x = 7.0; f(x) = 49.0
x = 7.5; f(x) = 56.25
x = 8.0; f(x) = 64.0
x = 8.5; f(x) = 72.25
x = 9.0; f(x) = 81.0
x = 9.5; f(x) = 90.25
x = 10.0; f(x) = 100.0
这是我的java代码:
import java.util.*;
public class PolyAreaTwo{
//method evalpoly Horner's rule
public static double evalpoly(double[] c, double x) {
int n = c.length - 1;
double y = c[n];
for (int i = n - 1; i >= 0; i--) {
y = c[i] + (x * y);
}
return y;
}
//main method
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n;
double a, b;
int nsteps;
//input degree
System.out.print("Enter degree of polynomial:");
n = in.nextInt();
//input n+1 coefficients
double[] c = new double[n+1];
for (int i=n; i>=0; i--) {
System.out.print("Enter coefficent " + i + ":");
c[i] = in.nextDouble();
}
for (double d : c) {
System.out.print(" x ^ " + d);
}
//input starting value x = a
System.out.println("Enter starting x: ");
a = in.nextDouble();
//input stopping value x = b
System.out.print("Enter stop x: ");
b = in.nextDouble();
//input number of steps between starting x and stopping x
System.out.print("Enter steps: ");
nsteps = in.nextInt();
//calculate size of each step
double s = (b-a)/nsteps;
int steps = 0;
//loop to call the evalpoly method
for (double x = a; x <= b; x += s) {
double y = evalpoly(c, x);
System.out.println("x ="+x+ " , y ="+y);
}
}
}
答案 0 :(得分:1)
删除不必要的外部while
循环后;请考虑在for
循环中使用您计算的步长:x += s
。
顺便说一句,通过将evalpoly()
初始化为y
,可以提高public static double evalpoly(double[] c, double x) {
int n = c.length - 1;
double y = c[n];
for (int i = n - 1; i >= 0; i--) {
y = c[i] + (x * y);
}
return y;
}
在{{1}}中的实施效率,如Horner's method和here所示最高阶系数。
{{1}}