首页 > 解决方案 > 在 C 中输入这个三角形的高度时打印帕斯卡三角形

问题描述

#include<stdio.h>
int factorial(int a){
    int b;
    if (a==0)
        return 1;
    else
        for (b=1;b<=a;b++)
        a=a*b;
}   //factorial of a
int pascal(int i, int j){

        return (factorial(i))/((factorial(j))*factorial(i-j));

}   
int main()
{
    int k,n,m,q;
    printf("Input m: ");
    scanf("%d", &m);
    for(k=0;k<m;k++){
        for(n=0;n<=k;n++)
            printf("%d ", pascal(k, n));

        printf("\n");
    }
}

我制作了一个打印帕斯卡三角形的程序,但是当我输入 m=6 时,如果 height<=3,它会给出正确的答案;它将打印:

1
1 1
1 3 1
1 0 0 1
1 0 0 0 1
1 0 0 0 0 1

你能帮我找出我的代码中的错误吗?

标签: c

解决方案


那是因为您在函数 factorial() 中编写了错误的逻辑。

for (b=1;b<=a;b++)
    a=a*b;//also , you have to return the value of a here!

这里,假设a = 3,那么在第一次迭代中,a = 3*1 等于3,在第二次迭代中,a=3*2 等于6;由于 6>3 ,循环终止,你得到了正确的答案!!但是如果 a = 4,那么在第一次迭代中,a = 4*1 等于 4,在第二次迭代中,a=4*2 等于 8,大于 4,因此循环不会进一步执行,你得到了错误的答案!正确的逻辑是,声明另一个 int 变量并将其初始化为 1 以存储“a”的乘积和变量本身,即,

 int fac=1;
    for(b=1;b<=a;b++){
        fac = fac*b;
    }
    return fac;

所以,完整的代码将是,

#include<stdio.h>
int factorial(int a){
int b=0;
if (a==0)
    return 1;
else{

   /* for(b=1;b<=a;b++){         
        fac = b*(factorial(b-1));// another way to find factorial using recursion
return fac;    
}*/
    int fac=1;
    for(b=1;b<=a;b++){
        fac = fac*b;
    }
    return fac;
  }

}   //factorial of a

int pascal(int i, int j){

    return factorial(i) / (factorial(j) *factorial(i-j));
 }
int main()
{
  int k,n,m,q;

   printf("Input m: ");
   scanf("%d", &m);

   for(k=0;k<m;k++){
    for(n=0;n<=k;n++)
        printf("%d ", pascal(k, n));

    printf("\n");
   }
   return 0;  // a good habit to add return 0, to let the compiler know that
             // the code is executed completely    
}

推荐阅读