1

我正在编写一个简单的 java 代码,它输出用户输入数字的所有因素。如何计算并显示输出的因子数量?

System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();

System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
    if(d % w == 0){
        System.out.println(w);
    } 
} 

在上面的代码中,它是'w'中输出的整数的个数,例如,如果输入的数字是8,它的因数是1,2,4,8,我如何写一个说'8有4个因数'的代码?

谢谢

4

3 回答 3

3

您只需要一个变量来计算因子:

System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;

System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
    if(d % w == 0){
        System.out.println(w);
        ++nFactors;
    } 
}
System.out.println(d + " has " + nFactors + " factors");
于 2013-11-03T20:13:31.097 回答
0

你需要一个计数器变量。这是代码:

int counter =0;

for(int w = 1; w <= d; w++ ){
        if(d % w == 0){
        counter++;   
        System.out.println(w);

        } 

System.out.println(d + " has " + counter + "factors ");
于 2013-11-03T20:15:28.357 回答
0

试试这个代码:

import java.util.Scanner;

public class EmbalzadoFactorial {
    public static Scanner sc;

    public static void main(String[] args) {
        int Number, i;
        sc = new Scanner(System.in);

        System.out.print("Please Enter any number to Find Factors: ");
        Number = sc.nextInt();

      System.out.println("The factors are: ");
        for(i = 1; i <= Number; i++) {
            if(Number%i == 0) { 

                System.out.format(" %d  ", i);
            System.out.print ("and");
            System.out.format("%s %n ", i);
            }
        }
    }
}
于 2016-06-28T01:54:28.080 回答