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);
}
}
当我使用+=
添加时,我得到a和b之间的加法结果。例如,如果a为2且b为5,则总和为14.当我使用*=
进行乘法时,我得到零。我需要帮助,因为我做错了,我得到的产品为零。
答案 0 :(得分:7)
任何时候0都是0.所以不要以product
的{{1}}开头,以0
开头。
1
答案 1 :(得分:3)
您需要设置
的值int product = 1;
而不是
int product = 0;
0乘以任何值将为0。
答案 2 :(得分:0)
你的代码是对的,但你犯了一个简单的数学错误。任何数字与0的乘积总是0.所以尝试使用1而不是0.这将解决问题。编辑后的代码如下所示:
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);
}
}