gpt4 book ai didi

Java 分解失败 - 为什么会循环?

转载 作者:行者123 更新时间:2023-12-02 04:17:37 24 4
gpt4 key购买 nike

我正在尝试获取代码来查找用户输入的因子,给出用户输入的素因式分解,并给出 lcm 和 gcm。这应该很简单。这是一门编程入门类(class),但对我来说进展太快了。我花了几个小时阅读和研究并试图让这段代码发挥作用。请帮忙。

import java.util.Scanner;


public class PattersonFactorization {


public static void main(String[] args)
{
//create scanner to obtain input from command window
Scanner input = new Scanner(System.in);

//initialization phase
int input1 = 0; //initialize first input from user
int input2 = 0; //initialize second input from user


//prompt twice for two inputs from user
//until they enter a positive value for each input

do
{
System.out.println("Please provide your first positive number: ");
input1 = input.nextInt();
}//end do for input1
while(input1 <= 0);

do
{
System.out.println("Please provide your next positive number: ");
input2 = input.nextInt();
}//end do for input2
while(input2 <= 0);

// call methods for factorization calculations
calculateFactors(input1);
calculateFactors(input2);
calculatePrime(input1);
calculatePrime(input2);
calculateLCM(input1, input2);
calculateGCF(input1, input2);


}//end of main

public static void calculateFactors(int input)
{

for(int countFactor = 1; countFactor < input; countFactor++)
{
if(countFactor % input == 0);
System.out.println(countFactor);
}

}//end of calculateFactors

public static void calculatePrime(int input)
{
for(int countPrime = 1; countPrime < input; countPrime++)
{
if(countPrime % input == 0);
System.out.println(countPrime);
input = input/countPrime;
countPrime--;
}
}//end of calculatePrime

public static void calculateLCM(int input1, int input2)
{
for(int factorNum = 1; input1 % factorNum != 0 && input2 % factorNum != 0; factorNum++)
System.out.println(factorNum);
}//end of calculateLCM

public static void calculateGCF(int input1, int input2)
{
for(int factorNum = input1; input1 % factorNum != 0 && input2 % factorNum != 0; factorNum--)
System.out.println(factorNum);
}

}//end of class

`

最佳答案

我相信问题出在这里:

        for(int countPrime = 1; countPrime < input; countPrime++)
{
if(countPrime % input == 0);
System.out.println(countPrime);
input = input/countPrime;
countPrime--;
}

您在递增循环中递减 countPrime。因此它的值永远不会改变。

关于Java 分解失败 - 为什么会循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137970/

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