Java 找到一个等于其每个数字的阶乘和的数,例如:145

Java 找到一个等于其每个数字的阶乘和的数,例如:145,java,Java,找到一个等于其每个数字的阶乘和的数,例如:145 从1到200 我试过这个: public static void main(String[] args) { int i = 0, x = 0, temp, temp1, digit = 0, factorial = 1, sum = 0; System.out.println("Special Numbers from 1 to 10,000 -:"); for (i = 1; i <= 200; i++) {

找到一个等于其每个数字的阶乘和的数,例如:145 从1到200 我试过这个:

public static void main(String[] args) {
    int i = 0, x = 0, temp, temp1, digit = 0, factorial = 1, sum = 0;
    System.out.println("Special Numbers from 1 to 10,000 -:");
    for (i = 1; i <= 200; i++) {
        temp = i;
        temp1 = i;
        while (temp > 0) {
            digit = temp % 10;
            factorial = 1;
            for (x = 1; x <= digit; x++) {
                factorial *= x;//factorial of digit
            }
            sum += factorial;//sum of factorial of a all the digits of the number
            temp = temp / 10;
        }
        if (sum == temp1) {
            System.out.println(temp1);
        }
    }
}
publicstaticvoidmain(字符串[]args){
int i=0,x=0,temp,temp1,digital=0,factorial=1,sum=0;
System.out.println(“1到10000之间的特殊数字-:”);
对于(i=1;i 0){
数字=温度%10;
阶乘=1;

对于(x=1;x您忘记了将sum设为0,因此您只能得到第一个数字的正确结果。行
sum=0;
应该在
之前,而(temp>0){

您的
sum
变量在for块之外声明

每次计算阶乘和时,都会将其添加到上一个和中,因此在这种情况下,
1!+4!+5!
永远不会是
145


尝试在循环内将其初始化为
0

您需要在
for
循环内初始化
sum

for(i=1;i<=200;i++){
    sum = 0; //<--include this
    temp = i;
    temp1 = i;
    while(temp>0){
        digit = temp%10;
        factorial =1;
        for(x = 1;x<=digit;x++){
            factorial*=x;//factorial of digit
        }
        sum+=factorial; //sum of factorial
        temp = temp/10;
    }
    if(sum == temp1){
        System.out.println(temp1);
    }
}

for(i=1;i“我得到了错误的输出”什么是错误的输出?什么是正确的输出?我猜您遇到了问题,因为145!要存储在
int
中要大得多。错误仅为“1”看起来不是145的阶乘,而是145位数字的阶乘之和,就像你的代码是复杂的和非结构化的。你应该在发布之前尝试构建你的代码,这样更容易理解你的想法。Thanx你是对的,很多人都被困在这个恼人的错误上了hours@RayyanMerchant很高兴我能帮上忙。你可以通过以下方式避免这些错误在循环内初始化变量。最好在while循环内执行
int sum=0;
。感谢您的建议,我们已经注意到了这一点