【问题标题】:Howto compute the factorial of x如何计算 x 的阶乘
【发布时间】:2011-04-16 17:14:24
【问题描述】:

如何得到整数x的值,用x!表示,它是数字1到x的乘积。

例如:5! 1x2x3x4x5 = 120.

int a , b = 1, c = 1, d = 1; 
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
     printf("%d x ", c);
     c++;
     d = d*a;
}
printf(" = %d", d);

【问题讨论】:

  • 从表面上看,变量 c 是多余的。
  • @Alexander:可能有人告诉他用 C++ 编写。

标签: c operators factorial


【解决方案1】:

如何得到整数 x 的 som,用 x! 表示,是数字 1 到 x 的乘积。

您的意思是 factorial of x 吗?

在循环内将d = d*a; 更改为d = d*b

【讨论】:

  • 您也可以 printf() 并乘以相同的变量!它们非常灵活,不会因共享使用而消失。
【解决方案2】:

你可以这样做:

for(b = 1; b <= a; b++) {
  d *= b;
}
// d now has a!

【讨论】:

    【解决方案3】:

    这是在大小和速度方面的最佳实现:

    int factorial(int x)
    {
        static const int f[13] = { 1, 1, 2, 6, 24, 120, /* ... */ };
        if ((unsigned)x < (sizeof f/sizeof f[0])) return f[x];
        else return INT_MAX+1; /* or your favorite undefined behavior */
    }
    

    提示:x!x 阶乘)不适合 int,除了非常非常小的值 x

    【讨论】:

    • 优秀的答案!我很高兴有人指出了严重的溢出问题。
    【解决方案4】:

    试试

    d = d * b;
    

    而不是

    d = d * a
    

    它应该可以正常工作

    【讨论】:

      【解决方案5】:

      您实际上有很多冗余代码,这可能就是您自己没有发现错误的原因。

      要计算阶乘,您只需要累加器(上述代码中的d)和输入(a)。为什么?

      【讨论】:

        【解决方案6】:

        我的代码不如其他代码好,但它对我有用:

        #include <iostream>
        using namespace std;
        
        unsigned int fattoriale (int n){
            if (n == 1){
                return 1;
            }
            else {
                return n * fattoriale(n-1);
            }
        }
        
        int main() {
            int tmp, num;
            cin >> num;
        
            tmp = fattoriale(num);
        
            cout << "Stampo il fattoriale del numero inserito: " << tmp << endl;
        
        }
        

        【讨论】:

          【解决方案7】:
          int factorial(int x)
          {
              int f;
              if (x == 0)
              {
                  f = 1;
              }
              else if (x > 0)
              {
               f = x*factorial(x-1);
              }
              return f;
          }
          
          int main()
          {
             int n = 0;
             cout << factorial(n);
          
             return 0;
          }
          

          【讨论】:

            猜你喜欢
            • 2015-04-19
            • 1970-01-01
            • 2022-01-17
            • 1970-01-01
            • 2023-03-22
            • 1970-01-01
            • 2013-02-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多