gpt4 book ai didi

java - 数字的乘积

转载 作者:行者123 更新时间:2023-12-02 01:05:16 24 4
gpt4 key购买 nike

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);
}
}

关于java - 数字的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60129476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com