c语言编程 巴斯卡三角形,在C中输入三角形的高度时打印帕斯卡三角形

#include

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

for(n=0;n<=k;n++)

printf("%d ", pascal(k, n));

printf("

");

}

}

我制作了一个打印帕斯卡三角形的程序,但是当我输入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

您能帮我找到代码中的错误吗?

答案

那是因为您在函数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

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

}*/

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

for(n=0;n<=k;n++)

printf("%d ", pascal(k, n));

printf("

");

}

return 0; // a good habit to add return 0, to let the compiler know that

// the code is executed completely

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值