我正在制作一个衍生计算器,询问用户多项式的程度,然后是每个项的系数,部分原因是因为我是一个没有经验的程序员,无法解析输入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;
}
Run Code Online (Sandbox Code Playgroud)
现在这是我的测试课.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
运行此操作会创建一个显示的小程序窗口
5.0x^0+
0.0
0.0
Run Code Online (Sandbox Code Playgroud)
这不是正确的衍生物.
我调试了我的程序,一切都按预期运行,直到视图切换到我的测试类并执行 g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
执行此行后,degree(多项式的次数)即使用户输入5也会重置为0.这样就会弄乱我班级中的所有for循环.
为什么会这样?有关修复此问题的建议吗?谢谢
您在构造函数中重新定义degree并value作为局部变量.它们使用相同的名称隐藏您的类变量.
不要重新声明它们.
代替
int degree = <something>;
double value = <something>;
Run Code Online (Sandbox Code Playgroud)
你需要
degree = <something>;
value = <something>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |