gpt4 book ai didi

java - Java 打印数组

转载 作者:行者123 更新时间:2023-11-30 03:03:50 26 4
gpt4 key购买 nike

我写了这个程序:

public class FunctionEvaluator {
public static Scanner console = new Scanner(System.in);

public static void main(String[] args) {
int degree;
System.out.print("What degree would you like your polynomial to be? ");
degree = console.nextInt();
int a[] = new int[degree + 1];
int coefficient;

for (int i = 0; i <= degree; i++) {
System.out.print("Coefficient of the x^" + (degree - i) + " term: ");
coefficient = console.nextInt();

a[i] = coefficient;
}

System.out.print("f(x) = ");

for (int i = 0; i < degree + 1; i++) {
System.out.print(a[i] + "x^" + (degree - i));

if (a[i] == degree) {
System.out.println(" ");
} else if (a[i + 1] >= 0 && a[i + 1] < degree) {
System.out.print(" + ");
} else if (a[i] < 0) {
System.out.print(" - ");
} else {
System.out.print(" ");
}
}

System.out.println();

int x;
int yN = 0;
double fOfX = 0;
double sum1;

do {
System.out.print("Give a value for x: ");
x = console.nextInt();
int deg = degree;
for (int i = 0; i <= degree; i++) {
sum1 = a[i] * Math.pow(x, deg);
deg--;
fOfX = fOfX + sum1;
}

System.out.println("f(" + x + ") = " + fOfX);

System.out.print("Do you want to go again (1 for yes and 0 for no)? ");
yN = console.nextInt();
} while (yN == 1);

System.out.println("Done.");

}

这段代码有一个问题:

System.out.print("f(x) = ");

for (int i = 0; i < degree + 1; i++) {
System.out.print(a[i] + "x^" + (degree - i));

if (a[i] == degree) {
System.out.println(" ");
} else if (a[i + 1] >= 0 && a[i + 1] < degree) {
System.out.print(" + ");
} else if (a[i] < 0) {
System.out.print(" - ");
} else {
System.out.print(" ");
}
}

主代码应该询问用户多项式的次数和系数,然后进行一些数学运算。如果我注释掉上面的代码段,程序就可以正常工作。但是,当我保留上面的代码(它应该打印出该函数)时,程序崩溃了。我怀疑这与 for 循环的限制有关,但无论我更改或修改什么,程序仍然崩溃。有人能告诉我出了什么问题以及为什么程序无法运行吗? IntelliJ 告诉我问题出在第一个 else if 行或 for 循环中的嵌套 if 语句(如果有帮助的话)。

最佳答案

您正在索引a[i+1],但a是int[ Degree + 1],因此在循环结束时您试图达到a [ Degree + 1],并且没有这样的项目,最后一个是[度]

可能您需要:

} else if (i < degree && a[i + 1] >= 0 && a[i + 1] < degree) {

顺便说一句,您的代码中还有另一个不合逻辑的部分。例如:

if (a[i] == degree) {

你将a[i]与度数进行比较,但它与度数无关。您可能想要比较i == Degree。请参阅此示例:

degree = 2
a[0] = 7, a[1] = 2, a[2] = 3 // 7 * x^2 + 2 * x + 3

如您所见,您应该将程度与索引进行比较,而不是与数组项的值进行比较。

我建议您在重写代码时牢记以下提示:尝试使用数组中的索引而不是“其他方式”。这会更加自然,并且每个索引都将是精确的指数:

a[2] = 7, a[1] = 2, a[0] = 3 // note: 3 * x^0 = 3 * 1 = 3

既然你无论如何都填充了数组中的所有元素,所以如果你以降序循环它并不重要。

关于java - Java 打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303323/

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