gpt4 book ai didi

java - 将任意数字转换为一位数

转载 作者:行者123 更新时间:2023-12-01 13:40:50 25 4
gpt4 key购买 nike

考虑数字 2345。如果将它的数字相乘,则得到数字 120。现在,如果再次将 120 的数字相乘,则将得到 0,即一位数。

import java.util.Scanner;

public class SmallestNum
{
int prod=1,sum=0;
void product(int m)
{
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
System.out.println(prod);
}


public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int x=scn.nextInt();
SmallestNum sn=new SmallestNum();
sn.product(x);
}
}

我可以从这段代码中得到120。但是我怎样才能用120做同样的过程并得到答案0。请帮助我。

最佳答案

您可以在 while 周围添加另一个循环,结束条件为 prod < 10 ,即只有一个数字。

void product(int m)
{
int prod;
do {
prod = 1;
while(m!=0)
{
int a = m%10;
m = m / 10;
prod *= a;
}
System.out.println(prod);
} while (prod >= 10);
}

关于java - 将任意数字转换为一位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20800224/

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