简体   繁体   中英

Java multiplying between two numbers

import java.util.Scanner;
public class Calculations {

  public static void main (String [] args) {

    Scanner console = new Scanner (System.in);
    int a = 0;
    int b = 0;
    int sum = 0;
    int product = 0;
    System.out.println ("Enter the Lower Bound");
    a = console.nextInt();
    System.out.println("Enter the Upper Bound");
    b = console.nextInt();

    while (a <= b) {
     product *= a;
     sum += a;
      a++;
    }
    System.out.println("The sum is " + sum);
    System.out.println("The Product " + product);

  }

}

When I use the += for addition I get the result for the addition between a and b. For example if a is 2 and b is 5 the sum will be 14. When I use *= for multiplication I get a zero. I need help in help in what Im doing wrong that Im getting a zero for the product.

任何时候0都是0。所以不要以0product开头,而以1开头。

int product = 1;

You need to set the value of

int product = 1;

instead of

int product = 0;

As 0 multiplied by anything will be 0.

You code is right but you made one simple mathematical mistake. The product of any number with 0 is always 0. So try to use 1 instead of 0. This will solve the problem. The edited code will look like this:

import java.util.Scanner;
public class Calculations 
{

   public static void main (String [] args) 
   {

      Scanner console = new Scanner (System.in);
      int a = 0;
      int b = 0;
      int sum = 0;
      int product = 1;
      System.out.println ("Enter the Lower Bound");
      a = console.nextInt();
      System.out.println("Enter the Upper Bound");
      b = console.nextInt();

      while (a <= b) 
      {
          product *= a;
          sum += a;
          a++;
      }
      System.out.println("The sum is " + sum);
      System.out.println("The Product " + product);
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM