在这里和谷歌搜索了几天,并询问了我的编程朋友。不幸的是,我仍然不明白如何更改我的代码......
我的程序计算给定数字的阶乘。然后它提供一个数字,表示阶乘答案包括多少位数。然后它将这些数字的值相加得出总数。
我的程序适用于 1 之间的任何数字!和 31 !...如果你放任何超过 31 的东西!(例如 50!或 100!)它不起作用,只是返回负数而不是总数。
我希望你们能指出我正确的方向或给我一些建议。我了解使用 BigIntegers 可能是一个解决方案,但我个人并不了解它们,因此来到这里。
任何帮助将非常感激。谢谢。
package java20;
/**
* Program to calculate the factorial of a given number.
* Once implemented, it will calculate how many digits the answer includes.
* It will then sum these digits together to provide a total.
* @author shardy
* date: 30/09/2012
*/
//import java.math.BigInteger;
public class Java20 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Using given number stored in factorialNo, calculates factorial
//currently only works for numbers between 1! and 31! :(
int fact= 1;
int factorialNo = 10;
for (int i = 1; i <= factorialNo; i++)
{
fact=fact*i;
}
System.out.println("The factorial of " + factorialNo +
" (or " + factorialNo + "!) is: " + fact);
//Using answer stored in fact, calculates how many digits the answer has
final int answerNo = fact;
final int digits = 1 + (int)Math.floor(Math.log10(answerNo));
System.out.println("The number of digits in the factorials "
+ "answer is: " + digits);
//Using remainders, calculates each digits value and sums them together
int number = fact;
int reminder;
int sum = 0;
while(number>=1)
{
reminder=number%10;
sum=sum+reminder;
number=number/10;
}
System.out.println("The total sum of all the " + digits
+ " idividual digits from the answer of the factorial of "
+ factorialNo + " is: " + sum);
}
}