#include <stdio.h>
int main() {
int a[10]={1,1,1,1,1,1,1,1,1,1};//1表示狐狸没进过,0表示进过
int i=0;//i表示数组元素标号
int n; //n表示循环进出洞的次数
for(n=0; n<1000; ++n)
{
i=i%10;
a[i]=0;
i=i+n+2;
}
for(i=0;i<10;i++)
{
if(a[i]==1)
{
printf("免子可能会在%d号洞里。\n",i+1);
}
}
return 0;
} #include<stdio.h> #include<stdlib.h> #include <string.h> #include <stdio.h> #define N 10 //法1 void main() { int i, j; //定义行、列下标。 int a[N][N] = {1,}; //定义二维数组用于储存杨辉三角。
for(i=1;i<N;i++)
for (j=0;j<=i;j++)
{
if(0 == j)
a[i][j] = 1;
else
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
//打印杨辉三角:
printf("您生成的%d阶杨辉三角如下:\n",N);
for(i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
if(a[i][j] != 0)
printf("%-5d",a[i][j]);
}
printf("\n");
}
}
//法2:打印杨辉三角形(打印10行)
#include <stdio.h> #define N 10
void main() { int i = 0; int j = 0;
int a[N][N] = {{1},{1},{1},{1},{1},{1},{1},{1},{1},{1}};
for(i=1;i<N;i++) //从第2行,第2列开始
for (j=1;j<=i;j++)
{
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
}
杨辉,字谦光,汉族,钱塘(今杭州)人,南宋杰出的数学家和数学教育家,生平履历不详。曾担任过南宋地方行政官员,为政清廉,足迹遍及苏杭一带。 他在总结民间乘除捷算法、“垛积术”、纵横图以及数学教育方面,均做出了重大的贡献。他是世界上第一个排出丰富的纵横图和讨论其构成规律的数学家。著有数学著作5种21卷,即《详解九章算法》12卷(1261),《日用算法》2卷(1262),《乘除通变本末》3卷(1274),《田亩比类乘除捷法》2卷(1275)和《续古摘奇算法》2卷(1275)(其中《详解》和《日用算法》已非完书)。后三种合称为《杨辉算法》。与秦九韶、李冶、朱世杰并称“宋元数学四大家”。
杨辉三角最本质的特征是,它的两条斜边都是由数字1组成的,而其余的数则是等于它肩上的两个数之和。
java代码
package algorithm;
public class YFTriangle { public static void main(String[] args) { yh(19); } /** * 它的两条斜边都是由数字1组成的,而其余的数则是等于它肩上的两个数之和。 * @param in */ public static void yh(int in){ int[] a = new int[in + 1]; int previous = 1; for (int i = 1; i <= in; i ++){ for (int j = 1; j <= i; j++){ int current = a[j]; a[j] = previous + current; previous = current; System.out.print(a[j] + " "); } System.out.println(); } } }
运行结果 ` 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
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
1 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 1
1 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 153 18 1 ` 出现负数 如果输入20行的话,那么最大的数将达到48620 如果你使用的是16位编译器(比如Tubro C),int型只占2字节,所以就会溢出, 导致出现负数。 解决办法
package algorithm;
public class YFTriangle { public static void main(String[] args) { yh(35); } /** * 它的两条斜边都是由数字1组成的,而其余的数则是等于它肩上的两个数之和。 * @param in */ public static void yh(int in){ long [] a = new long[in + 1]; long previous = 1; for (int i = 1; i <= in; i ++){ for (int j = 1; j <= i; j++){ long current = a[j]; a[j] = previous + current; previous = current; System.out.print(a[j] + " "); } System.out.println(); } } }