When n
reaches 1, n - 1
equals 0 and any number multiplied by zero equals zero. So fat
gets equal to 0 when you use n >= 1
.
I checked one and found the answer to your second question. The data types in java have limits and peculiarities. When a number in double becomes large, it is now expressed in scientific notation, with E being the exponent of the base 10 of the scientific notation.
Here's a chart of how JAVA shows factorial numbers in different types:
n, int, Integer, long, float, double
n = 1, 1, 1, 1, 1.0, 1.0
n = 2, 2, 2, 2, 2.0, 2.0
n = 3, 6, 6, 6, 6.0, 6.0
n = 4, 24, 24, 24, 24.0, 24.0
n = 5, 120, 120, 120, 120.0, 120.0
n = 6, 720, 720, 720, 720.0, 720.0
n = 7, 5040, 5040, 5040, 5040.0, 5040.0
n = 8, 40320, 40320, 40320, 40320.0, 40320.0
n = 9, 362880, 362880, 362880, 362880.0, 362880.0
n = 10, 3628800, 3628800, 3628800, 3628800.0, 3628800.0
n = 11, 39916800, 39916800, 39916800, 3.99168E7, 3.99168E7
n = 12, 479001600, 479001600, 479001600, 4.790016E8, 4.790016E8
n = 13, , , 6227020800, 6.2270208E9, 6.2270208E9
n = 14, , , 87178291200, , 8.71782912E10
n = 15, , , 1307674368000, , 1.307674368E12
n = 16, , , 20922789888000, , 2.0922789888E13
n = 17, , , 355687428096000, , 3.55687428096E14
n = 18, , , 6402373705728000, , 6.402373705728E15
n = 19, , , 121645100408832000, , 1.21645100408832E17
n = 20, , , 2432902008176640000, , 2.43290200817664E18
n = 21, , , , , 5.109094217170944E19
Source: link
To display without scientific notation you can format the double number using printf with% f (see this page for more printf options: link )
Follow the code I ran to test:
public class Fatorial
{
public static void main(String[] args)
{
double numero = 11;
double n = numero; //contador
double fat = n; // crio uma variável para calcular e atribuo o valor do spinner à ela
while (n > 1)
{
fat = fat * (n-1);
n--; //decremento do valor da multiplicação
}
System.out.println("O fatorial de " + numero + " é: " + fat + " (double padrão com notação científica)");
System.out.printf("Fatorial Double formatado: %.0f\n", fat);
}
}
Output on console:
O fatorial de 11.0 é: 3.99168E7 (double padrão com notação científica)
Fatorial Double formatado: 39916800