作业帮 > 综合 > 作业

编写程序,打印如下的杨辉三角形:

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/15 17:31:10
编写程序,打印如下的杨辉三角形:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
c++
public static void main(String[] args) {
textYH yang = new textYH();
yang.printYanghuiTriangle(5);
}
/**
* 生成指定行数的杨辉三角形
*
* @param lines 杨辉三角形的行数
*/
public void printYanghuiTriangle(int lines) {
if(lines < 1) {
throw new IllegalArgumentException("lines must be great than 0.");
}
if(lines > 30) {
throw new IllegalArgumentException("lines is too big.");
}
int[] line = new int[lines];
int maxLen = getMaxLen(lines);
for(int i = 0; i < lines; i++) {
line[0] = line[i] = 1;
for(int j = 1,k = i / 2,pre = line[0]; j 0 start :1L;
while(num > start) {
result *= num--;
}
return result;
}
/**
* 根据指定数字计算数字的长度
* @param num 数字
* @return 数字的长度
*/
private int getLength(long num) {
int len = 0;
while(num > 0L) {
num /= 10L;
len++;
}
return len;
}
private void printLine(int[] yanghui,int line,int width) {
printSpaces((yanghui.length - line) * width);
for(int i = 0; i < line; i++) {
if(i > 0) {
printSpaces(width);
}
printSpaces(width - getLength(yanghui[i]));
System.out.print(yanghui[i]);
}
System.out.println();
if(width > 1) {
System.out.println();
}
}
private void printSpaces(int spaceCount) {
for(int i = 0; i < spaceCount; i++) {
System.out.print(" ");
}
}