c - C 语言中的帕斯卡三角形及其组合

标签 c combinations factorial pascals-triangle

#include <stdio.h>
long factorial(int num)
{
    int counter;
    int fact = 1;
    for (counter = num; counter > 0; counter--) fact *= counter;
    return fact;
}

float combinations(int n, int k)
{
    int numerator = factorial(n);
    int denominator = factorial(k) * factorial(n-k);
    float fraction = numerator/denominator;
    return fraction;
}
int main()
{
    printf("How many rows of Pascal\'s triangle should I print?\t");
    int rows = GetInteger();
    int counter;
    int counter2;
    for (counter = 1; counter <= rows; counter++)
    {
        int y = rows-counter;
        for (; y > 0; y--) printf("   ");
        for (counter2 = 0; counter2 <= counter; counter2++)
                printf("%6.0lu", (long) combinations(counter, counter2));
        printf("\n");
    }
}

每当我超过十二行时,数字就会开始减少。我做错了什么?

而且,GetInteger() 只是一个带有一些修饰的 scanf()。我 100% 确定它可以完美运行。

最佳答案

在第 12 行阶乘之后,pascal 三角形元素变得太大,因此 int 类型无法容纳它们 - 因此您会溢出(您获得的值很可能包含在最大 int 值周围)。

附言为什么在代码中使用 3 种不同的类型(long、int、float)?作为 k!*(n-k)!总是除以 n!你不需要浮点值(你使用整数除法并将结果转换为 long 无论如何)。只需使用最大的整数类型,或一些可以容纳任意长度整数的自定义 BigInt 类型 - 这样您就可以为大行号显示正确的值。

关于c - C 语言中的帕斯卡三角形及其组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5169791/

相关文章:

c - 将多行文本解析为单独的字符串

python - python中枚举所有组合并返回索引的最快方法

php - 如何返回给定字符串的所有组合? (例如 'foo bar' = bar、bar_foo、foo)

带有线程池的Java阶乘计算

C - 使用 unsigned int 是否只是糟糕的编码实践?

c - gethostbyname 和 gethostbyaddress - 结构在内存中的位置

c++ - 在不移动数据的情况下在 CUDA 中实现 realloc

MySQL 快速检查 hash 是否存在

无法计算大于 20 的阶乘! !怎么做?

python - python中简单阶乘函数的空间复杂度