如何在 C 中的阶乘循环中找到阶乘 while 循环中数字的平方



我正在尝试创建一个程序,该程序不仅可以计算数字的阶乘,还可以显示阶乘小于该数字平方的输出。

这些是要求:键入一个介于 3 到 9 之间的数字。它在输出中同时显示其阶乘和平方。如果插入的数字的阶乘小于数字的平方,则输出字符串"Gotcha!

这是我到目前为止的代码。谢谢

#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: %dn", num, fact);
        return 0;
    }
}
}

只需通过将数字乘以自身来计算数字的平方即可。

square = num * num;
printf("Square of %d is: %dn", num, square);
if (fact < square)
    printf("Gotcha!n");

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> (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

尝试这样的事情:

#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("%sn", "Gotcha!");
    }else{
        printf("Factorial of %d is: %dn", num, fact);
    }
    return NO_ERRORS;
}

谢谢

最新更新