c - 在 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
你能帮我找出我的代码中的错误吗?
解决方案
那是因为您在函数 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
}
推荐阅读
- python - 使用 numpy 在循环中创建矩阵
- javascript - 使用 JavaScript API 在 Google Drive 上自定义 mime 类型会中断编码
- c - GLib - class_init 和 init 类方法之间的区别
- php - Woocommerce 预订中每个人和项目的动态结帐自定义字段
- java - 如何使用 android 从 Azure IoT 中心读取设备到云?
- swagger - Phalcon Zircote/Swagger-php 安全错误
- sql - SQL 组用户,如果他们属于一个或多个组
- c# - 在 NHibernate 中为 linq 生成平均时间跨度的方法
- javascript - 迭代对象中的嵌套数组以整理信息
- java - java中对数组进行排序的算法