获得产品

时间:2013-10-19 22:10:44

标签: java product

我正在进行初学者级别的java编程练习,而且我一直坚持要求:

“编写一个名为Product1ToN的程序来计算整数1到10的乘积(即1×2×3×...×10)。尝试计算1到11,1到12之间的乘积,记下所获得的产品并解释结果。 提示:声明一个名为product的int变量(用于累积产品)并初始化为1.“


到目前为止我所做的是:

 public static void Product1ToN() {

    int product;

    for(int number = 1; number <= 10; number++){
        product = number*number;
        System.out.println(product);
    }
}

如何编写它来获取整数的产品?

3 个答案:

答案 0 :(得分:4)

在每次迭代中,您希望将当前产品乘以当前数字:

int product = 1;
for(int number = 1; number <= maxNum; number++){
    product *= number;

}
System.out.println(product);

答案 1 :(得分:1)

public static void Product1ToN(int N) {
    int product = 1;
    for (int number = 2; number <= N; number++) product *= number;
    System.out.println(product);
}

答案 2 :(得分:0)

import java.util.Scanner;
public class Test
{
    public static void main (String[] args)
    {
        int x,Snum,Lnum;
        int product = 1;
        Scanner sc = new Scanner (System.in);
        System.out.println("Enter starting point number");
        Snum = sc.nextInt();
        System.out.println("Enter Ending point number");
        Lnum = sc.nextInt();
        for (x=Snum; x<=Lnum; x++)
        {
            product *= x;           
        }
        System.out.println("product of numbers = "+product);
    }
}