2014-10-19 7 views
0
public static void main (String[] args) 
{ 
    Scanner sc = new Scanner(System.in); 
    int number; 
    System.out.println("Enter a number to find the factorial of it: ");  
    number= sc.nextInt(); 
    int factor=1; 
    if (number<0 && number>10) 
    { 
     System.out.println("Invalid!! the number has to be between 1 and 10"); 
    } 
    for(int x=1; x<=number; x++) 
    {  
     factor = factor*x;    
     System.out.println("The factorial of "+number+" is = " +factor); 
    } 

} 

Можете ли проверить мой код @TNT? скажите мне, если это то, что у хотел, чтобы яПрименение использования функций и процедур

+0

да, например, 5 = 1 * 2 * 3 * 4 * 5 –

+0

как бы я сделать это, потому что я может использоваться только для факториального использования для циклов, и мы можем использовать для циклов в методе функций –

+1

@Makoto: алгоритм кажется правильным. Оператор System.out должен, вероятно, отображать 'x', а не' number' на каждой итерации. – Voicu

ответ

1

Вот возможное решение:

Scanner sc = new Scanner(System.in); 
int number; 
System.out.println("Enter a number to find the factorial of it: "); 
number= sc.nextInt(); 
int factor = 1; 
// edit the condition so numbers that fall outside the range 0-10 will cause the error 
// message to display 
if (number < 1 || number > 10) 
    System.out.println("Invalid!! the number has to be between 1 and 10"); 
else { 
    for(int x=1; x<=number; x++) 
    { 
     factor = factor*x; 
    } 
    System.out.println("The factorial of "+number+" is = " +factor); 
} 
+0

Я очень ценю, что помог мне :), спасибо alot –

+0

Есть ли способ, которым я могу задать вопрос, не помещая никакого кода –

+0

Следуйте [this] (http://stackoverflow.com/help/how-to-ask) и [this] (http: // stackoverflow.com/help/mcve), и все должно быть в порядке. – TNT

Смежные вопросы