2016-04-24 53 views
-2

我試圖創建一個程序,不僅計算數的階乘,但是在階乘是小於該數值的平方也顯示輸出。如何在C中的Factorial while循環中查找數字的平方?

這些是要求: 您鍵入3到9之間的數字。 它在輸出中顯示其階乘和其平方。 如果插入的數的階乘是小於號,輸出字符串的廣場「疑難雜症!」

這是我的代碼到目前爲止。謝謝

#pragma once 
#include <stdio.h> 
#define MIN 3 
#define MAX 9 
#define _CRT_SECURE_NO_WARNINGS 

int main() 
{ 
int i, fact = 1, num; 
printf("Enter a number:\n"); 
scanf_s("%d", &num); 

while (num >= MIN || num <= MAX) 
{ 
    for (i = 1; i <= num; i++) 
    { 
     fact = fact*i; 
    } 
    if (num < MIN || num > MAX) 
    { 
     printf("Out of range. Please try again.\n"); 
     scanf_s("%d", &num); 
    } 
    else 
    { 
     printf("Factorial of %d is: %d\n", num, fact); 
     return 0; 
    } 
} 
} 
+0

編輯源和並添加標題那裏。 – randominstanceOfLivingThing

回答

1

只是通過乘以它自己來計算數字的平方。

square = num * num; 
printf("Square of %d is: %d\n", num, square); 

if (fact < square) 
    printf("Gotcha!\n"); 
1

r.e.務實的態度,我同意bodangly。

R.E.你的問題背後的理論,讓我們挖成一個小...

編輯:沒看夠深,而不是永遠我的回答應該是「大多從來沒有(只有兩次對於n = 2和n = 3) 。

回顧一下你的問題: 鑑於「N」找出是否「N的階乘」小於「N的平方」

我們可以用概括的:

n! < n^2 

我們來拋這個局面,使其更容易操作:

n! < n^2 
n^2 > n! 
n * n > n * (n-1) * (n-2) * .. * 1 

如果我們將每邊除以n,我們得到以下結果。

n > (n-1) * (n-2) * .. * 1 
n > (n-1)! 

所以問題變成:對於n的值是多少(n-1)! ? (擾流警報:不是很頻繁)

讓我們來看看,看看當n>(N-1)!

考慮這個表...

+------------+----+-----+----------+-------------------------+ 
| n > (n-1)! | n | n-1 | (n-1)! | notes...    | 
+------------+----+-----+----------+-------------------------+ 
|  no | 0 | -1 | undef | (-1)! is undefined  | 
|  no | 1 | 0 |  1 | 0! is 1 by definition | 
|  yes | 2 | 1 |  1 | 1! is 1 by definition | 
|  yes | 3 | 2 |  2 | (or 2 * 1)   | 
|  no | 4 | 3 |  6 | (or 3 * 2 * 1)  | 
|  no | 5 | 4 | 24 | (or 4 * 3 * 2 * 1) | 
+------------+----+-----+----------+-------------------------+ 

這是指N >(N-1)!僅當n = 2和n = 3時纔是如此。

+0

感謝您的解釋!對此,我真的非常感激。我會把它當作便條:) – crhodes

0

嘗試這樣:

#include <stdio.h> 

#define MIN 3 
#define MAX 9 
#define _CRT_SECURE_NO_WARNINGS 

enum {NO_ERRORS, ERROR}; 
enum {FALSE, TRUE}; 


int main() 
{ 
    int i, fact = 1, num, valid = FALSE, sqr; 

    while(!valid){ 

     printf("Enter a number:\n"); 
     scanf("%d", &num); 

     if (num < MIN && num > MAX){ 
      printf("Out of range. Please try again.\n");    
     }else{ 
      valid = TRUE;      
     } 
    } 

    /* get the factorial */ 
    for (i = 1; i < num; i++){ 
     fact = fact * i; 
    } 

    /* get the square */ 
    sqr = num * num; 

    /* output */ 
    if(fact < sqr){ 
     printf("%s\n", "Gotcha!"); 
    }else{ 
     printf("Factorial of %d is: %d\n", num, fact); 
    } 

    return NO_ERRORS; 
} 

感謝

+0

不,謝謝!對此,我真的非常感激。 :) – crhodes