0
Factorial - Java Help me to fix this please
Here is the question The factorial of a number N is equal to 1 * 2 * 3 * ... * N For example, the factorial of 5 is 1* 2 * 3 * 4 * 5 = 120. Create a program that takes a number from input and output the factorial of that number. This is my answer to this. But it's not taken as the correct answer and also not getting any error what's wrong with this code. help me to solve this import java.util.Scanner; class Demo{ public static void main(String[] args) { long fact = 1; Scanner sc = new Scanner(System.in); int x = sc.nextInt(); for(int i=1; i<=x; i++){ fact = fact * 1; } System.out.println(fact); } }
3 Respostas
+ 4
Focus on the code inside the loop:
fact = fact * 1
What is the result of multiplying fact by 1?
+ 1
Try below code it is working fine.
https://sololearn.com/compiler-playground/col1g5N2TqJT/?ref=app
0
The problem in your code is this " fact = fact * 1; " .. think about that .. if x is 3 for example .. you're gone multiply fact with 1 ..3 time(1*1, 1*1, 1*1) .. to make it work.. you need to multiply fact by x .. " fact *= x " so that you can get .. the right rezult.. if you multiply fact with x you get the next rezult (1*1, 1*2, 1*3) etc..