When n
reaches 1, n - 1
is equal to 0 and any number multiplied by zero is equal to zero. Therefore fat
is equal to 0 when you use n >= 1
.
I did a search and found the answer to your second question. Java data types have limits and particularities. When a double number becomes large it becomes expressed in scientific notation, where E is the exponent of base 10 of scientific notation.
Here is a table of how JAVA shows factor 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: http://webtutsdepot.com/factorial-table-and-the-associated-data-type-limits-in-java/
To display without scientific notation you can format the double number using printf with %f (see this page for more printf options: https://sharkysoft.com/archive/printf/docs/javadocs/lava/clib/stdio/doc-files/specification.htm )
Follow the code I’ve run 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
Also put the code with the
double
so we can understand what it is you tried to do that ended up producing these hexadecimal numbers.– Victor Stafusa