我正在制作一个导数计算器,向用户询问其多项式的阶数,然后询问每个项的系数,部分原因是我不是一个经验丰富的程序员,并且无法解析3x^4/4 + sin(x)
之类的输入。
这是我的课。
package beta;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class DerivativeCalculator
{
public DerivativeCalculator(String d, String v)
{
int degree = Integer.parseInt(d);
double value = Double.parseDouble(v);
coeffList = new ArrayList<Double>();
for (int i = 0; i <= degree; i++)
{
String console = JOptionPane.showInputDialog("Enter the coefficient of the "
+ "x^" + i + " term.");
Double coeff = Double.parseDouble(console);
coeffList.add(coeff);
}
}
public double calc()
{
double dx = 0.0001;
double x1 = value;
double y1 = 0;
for (int d = degree; d >= 0; d--)
{
y1 += coeffList.get(d) * Math.pow(x1, d);
}
double x2 = x1 + dx;
double y2 = 0;
for (int d = degree; d >= 0; d--)
{
y2 += coeffList.get(d) * Math.pow(x2, d);
}
double slope = (y2 - y1)/ (x2 - x1);
DecimalFormat round = new DecimalFormat("##.##");
round.setRoundingMode(RoundingMode.DOWN);
return Double.valueOf(round.format(slope));
}
public String getEquation()
{
String equation = "";
for (int d = degree; d >= 0; d--)
{
equation = equation + String.valueOf(coeffList.get(d)) + "x^" + String.valueOf(d) + " + ";
}
return equation;
}
public String getValue()
{
return String.valueOf(value);
}
private int degree;
private double value;
private List<Double> coeffList;
}
现在这是我的测试课。
package beta;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
public class DerivativeCalculatorTest extends JApplet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
String d = JOptionPane.showInputDialog("Enter the degree of your polynomial: ");
String v = JOptionPane.showInputDialog("Enter the x value "
+ "at which you want to take the derivative");
DerivativeCalculator myDerivCalc = new DerivativeCalculator(d, v);
g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
g2.drawString(myDerivCalc.getEquation(), 10, 40);
g2.drawString(myDerivCalc.getValue(), 10, 70);
}
}
运行此命令将创建一个显示小程序窗口
5.0x^0+
0.0
0.0
这不是正确的导数。
我调试了程序,一切正常运行,直到视图切换到测试类并执行
g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
执行完此行后,即使用户输入了5,
degree
(多项式的次数)也重置为0。这将使我的类中的所有for循环陷入混乱。为什么会这样?有什么建议解决这个问题吗?谢谢
最佳答案
您将degree
和value
重新定义为构造函数中的局部变量。它们shadow您的类变量具有相同的名称。
不要重新声明它们。
代替
int degree = <something>;
double value = <something>;
你需要
degree = <something>;
value = <something>;