import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt(); //输入rows,行
for (int i = 0; i < rows; i++) { //共rows行
int number = 1; //控制所有数字输出
System.out.format("%" + (rows - i) * 2 + "s" , "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
//是不是感觉这代码看不懂,其实我也看不懂,文章后面我再补一个自己写的源码
了解新知识点
-
杨辉三角基本实现语法
-
格式化输出
System.out.format();
我去查过资料,这里的`System.out.format` 与`System.out.printf`语法意思是一样的,printf语法直接调用了format
- 格式化输出%s,%d灵活用法
System.out.format("%" + (rows - i) * 2 + "s" , "");
System.out.format("%4d",number);
为了方便理解,随便讲下%f,Java中,%d和%f表示输出时,替换整型输出和浮点输出的占位符。
如:
int a = 28;
float b = 13.0f;
System.out.printf("整数是:%d%n小数是:%.2f",a,b); //这里的%n是换行的格式字符串,只能用在print输出语句中, 而n是回车字符, 可以用在所有的字符串中. **%.1f就是保留一位小数,这就是格式化输出**
输出结果为: 整数是:28 //这里的%d可以写%4d、%5d都是可以的,数字只是参数
小数是:13.00;
上面代码看不懂的试试看看这个:源码2
import java.util.Scanner;
// 定义公开类 Test
public class Test{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] yanghui = new int[n][]; //n长n宽的数组
for(int i = 0; i < yanghui.length; i++){ //遍历数组每个元素
yanghui[i] = new int[i + 1]; //给每个一维数组(行)赋值
for(int j = 0; j < yanghui[i].length; j++){
if(j == 0 || j == yanghui[i].length -1){
yanghui[i][j] = 1;
}else{
yanghui[i][j] = yanghui[i - 1][j] + yanghui[i - 1][j - 1];
}
}
}
//输出杨辉三角
for (int i = 0 ; i < yanghui.length; i++){
System.out.format("%" + ((n - i) * 2) + "s",""); //第一行才是最后一行!这个语句太6了,一下把我整明白了
for (int j = 0; j < yanghui[i].length; j++){
System.out.printf("%4d",yanghui[i][j]);
}
System.out.println();
}
}
}



