1

所以我想创建一个程序,当用户输入一个值 c 和 a = 1 时,它会打印出一个可分解的二次方程。程序应确定 b 的所有可能整数值,以便三项式以 x^2 + bx + c 的形式打印出来

例如,如果用户为 c 输入 -4,程序应打印出:
x^2 - 4
x^2 - 3x - 4

到目前为止,这就是我对我的代码所做的事情,我试图弄清楚如何执行程序,但我真的很难从这里去哪里。如果有人可以提供一些帮助,将不胜感激!

public class FactorableTrinomials
{
    public static void main (String [] args)
    {
        Scanner scan = new Scanner(System.in);


        System.out.println("A trinomial in standard form is ax^2 + bx + 
        c. \nIf a = 1, this program will output all factorable trinomials 
        given the entered c value.");

        System.out.print("\nEnter an integer “c” value: ");
        int numC = scan.nextInt();

        final int NUMA= 1;
        int numB;


        if (numC > 0)
        {
            int factors;

            System.out.print("\nThe factors of " + numC + " are: ");

            for(factors = 1; factors <= numC; factors++)    //determines 
            factors and how many there are
            {
                if(numC % factors == 0)
                {
                    System.out.print(factors + " ");
                }
            }
4

1 回答 1

0

首先,找到与 c 相乘的整数对。然后 b 的所有可能值将是这对整数的总和。

查找整数对的一种简单方法是将 2 个变量从 -c 循环到 c 并检查乘积是否为 c。例如:

for(int i = -1 * numC; i <= numC; i++) {
    for(int j = -1* numC; j<= numC;j++) {
        if(i * j == numC) {
            int b = i + j;

            //print solution, if b == 0 then don't print the second term
        }
    }
}
于 2018-02-09T03:30:12.113 回答