数字的乘积

  • 本文关键字:数字 java
  • 更新时间 :
  • 英文 :

public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int product = 1; 
if (x >=0 && x<=9) {
System.out.println(x);
}
else  {         
product = product * (x % 10); 
x = x/10;
System.out.println(product);
}

当输入为负数时,乘积介于第一位和最后一位数字之间。谁能解释一下?我试图Math.abs()获得绝对价值,但这是不可能的,现在它正在杀死我。

按如下方式操作:

import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int ç = 1;
int product = 1;
if (x == 0) {
product = 0;
} else {
while (x > 0) {
product *= x % 10;
x /= 10;
}
}
System.out.println(product);
}
}

示例运行-1:

Enter an integer: -256
60

示例运行-2:

Enter an integer: 0
0

示例运行-3:

Enter an integer: 9
9

示例运行-4:

Enter an integer: 256
60

递归版本:

import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
System.out.println(productOfDigits(n));
}
static int productOfDigits(int n) {
n = Math.abs(n);
if (n > 0 && n < 10) {
return n;
}
if (n == 0) {
return 0;
}
return (n % 10) * productOfDigits(n / 10);
}
}

您可以使用 javaMath.log10()函数来获取位数,然后根据它计算第一个数字:

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number < 0) {
number *= (-1);
}
int digits = (int) Math.log10(number);
int lastDigit = number % 10;
int firstDigit = (int) (number / Math.pow(10, digits));
int product = lastDigit * firstDigit;
System.out.println(product);
}

当然,如果你的数字是负数,你可以使用Math.abs()(而不是if(

您当前的代码只打印出输入整数的最后一位数字,因为您只执行product = product * (x % 10);(可以简化为product *= x % 10;(和x = x / 10;(可以简化为x /= 10;(一次。您应该重复执行这两个操作,直到x为 0。

为此,您可以使用 for 循环或 while 循环。以下是使用 for 循环编写此内容的方法:

for (; x > 0 ; x /= 10) {
product *= x % 10;
}

if语句的条件也可以更改为x == 0,因为x值 1-9 都可以由else子句正确处理。

最新更新