gpt4 book ai didi

java - 二次方程因子计算

转载 作者:行者123 更新时间:2023-12-01 22:22:55 24 4
gpt4 key购买 nike

关于二次方程(了解更多 here ),我将方程的 abc 视为输入。

示例方程如下:21x^2 - 8x - 4 这里,a = 21,b = -8,c = -4。所以,在求解时(没有公式), => 21x^2 - 14x + 6x - 4 = 0。

我需要中间的两个数字,即本例中的 14 和 6(读取因子)。我想我都做对了,但是输入似乎是无限的,根本不会停止。你能纠正这个错误吗?我也很好奇为什么会发生这种情况。

import java.util.Scanner;
public class QuadFact {
static Scanner sc = new Scanner(System.in);
static int a,b,c;
static int P, diff, p;
static int i;
static boolean found = false;

void accept(){
System.out.println("Enter the a, b, c");
a = sc.nextInt(); b = sc.nextInt(); c = sc.nextInt();
}

void compute(){
P = a * c;
diff = 0;
while(!found){
for (i = b + 1;;i++){
diff = i - b;
p = i * diff;
if (p==P) {
found = true;
break;
}
}
}
}

void display(){
System.out.print("These are the raw numbers, should be correct.
Still,\n it is advisable you verify it.");
System.out.println("One factor: " + i);
System.out.println("Other factor: " + diff);
}

public static void main(String[] args){
QuadFact a = new QuadFact();
a.accept();
a.compute();
a.display();
}
}

最佳答案

我认为你必须在 b 的“两侧”寻找加起来为 b 并产生乘积 a*c 的因子对。

void compute(){
P = a * c;
while(!found){
for( i = 1; ; i++ ){
diff = b - i;
if (i * diff == P) {
found = true;
break;
}
diff = b + i;
if (-i * diff == P) {
found = true;
break;
}
}
}
}

关于java - 二次方程因子计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368389/

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