-1

我正在尝试输出一个左对齐的帕斯卡三角形。程序应首先通过提示“N:”从用户那里读取一个正整数 N。然后,程序将在屏幕上打印帕斯卡三角形的前 N ​​行。但是,我认为我的外部两个 for 循环存在问题。而不是得到 (N=3)
1
1,1
1,2,1

我得到
1
1,2
2,4,4


#include <stdio.h>
int main(void) {

    int input,i,j,k,p,N,x;
    int f1=1;
    int f2=1;
    int f3 = 1;

    printf("N:");
    scanf("%d",&N);

    for(i=1;i<=N;i++){
        for(j=1;j<=i;j++){
            for(x = 1; x<= N-1; x++){
                f1 = f1 * x;
            }
            for(x = 1; x <= j-1; x++){
                f2 = f2 * x;
            }
            for(x = 1; x <= N-j; x++){
                f3 = f3 * x;
            }
            p= (f1)/(f2*f3);

            if(j==i)
                printf("%d",p);
            else
                printf("%d,",p);
        }
        printf("\n");

    }



    return 0;
}
4

2 回答 2

1

帕斯卡三角公式:C(n,k) , n C k = n!/(k! * (nk)!)
试试这个代码:

#include <stdio.h>
int main(void) {
    int i,j,p,N,x;
    int f1=1;
    int f2=1;
    int f3 = 1;

    printf("N:");
    scanf("%d",&N);

    for(i=0;i<=N;i++){      
        for(j=0;j<=i;j++){
            f1=f2=f3=1;  //after each calculation change value to default otherwise it will take old value.
            for(x = 1; x<= i; x++){ // run upto x<=i
                f1 = f1 * x;
            }
            for(x = 1; x <= j; x++){ //run upto x<=j
                f2 = f2 * x;
            }
            for(x = 1; x <= i-j; x++){ //run upto x<=i-j
                f3 = f3 * x;
            }
            p= (f1)/(f2*f3);

            if(j==i)
                printf("%d",p);
            else
                printf("%d,",p);
        }
        printf("\n");

    }
return 0;
}

在计算一个值后,您不会将其更改为默认值,因此它使用旧值进行下一次计算并给出错误的输出。
所以f1=f2=f3=1;在每次计算后使用。

于 2015-02-04T06:47:16.993 回答
0

您需要在每次迭代时将f1f2和设置f3为 1,而不仅仅是第一次迭代。您还需要调整循环边界。

#include <stdio.h>

int main(void)
{
    int N;

    printf("N: ");
    scanf("%d", &N);

    printf("Pascal triangle for N = %d\n", N);

    for (int i = 0; i <= N; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            int f1 = 1;
            int f2 = 1;
            int f3 = 1;
            for (int x = 1; x<= i; x++)
                f1 *= x;
            for (int x = 1; x <= j; x++)
                f2 *= x;
            for (int x = 1; x <= i-j; x++)
                f3 *= x;
            int p = (f1)/(f2*f3);

            if (j == i)
                printf("%d", p);
            else
                printf("%d,", p);
        }
        printf("\n");
    }

    return 0;
}

示例输出:

$ ./pascal
N: 7
Pascal triangle for N = 7
1
1,1
1,2,1
1,3,3,1
1,4,6,4,1
1,5,10,10,5,1
1,6,15,20,15,6,1
1,7,21,35,35,21,7,1
$
于 2015-02-04T06:53:25.943 回答