Java程序打印星形帕斯卡三角形
在这篇文章中,我们将了解如何在Java中打印星形帕斯卡三角形。帕斯卡三角形是使用多个for循环和print语句生成的。三角形外的所有值都被认为是零(0)。第一行是0 1 0,而只有1占据帕斯卡三角形中的一个空格,0是不可见的。第二行是通过添加(0+1)和(1+0)得到的。输出夹在两个零之间。这个过程持续到达到所需的级别。
问题陈述
编写一个Java程序来打印星形帕斯卡三角形。下面是相同的演示:
输入
Enter the number of rows in Pascal's Triangle : 8
输出
Enter the number of rows in Pascal's Triangle : 8
The Pascal's Triangle :
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
使用用户输入
以下是打印星形帕斯卡三角形的步骤:
- 从java.util包导入Scanner类。
- 我们将定义方法并计算数字的阶乘,并将计算二项式系数。
- 创建Scanner对象以获取用户输入,并将使用nextInt()获取行数。
- 使用嵌套循环生成帕斯卡三角形,以动态地格式化和计算值。
示例
在这里,输入是根据提示由用户输入的。你可以在我们的代码练习工具
中实时尝试此示例。
import java.util.Scanner;
public class PascalsTriangle {
static int factorial(int my_input) {
int factors;
for(factors = 1; my_input > 1; my_input--){
factors *= my_input;
}
return factors;
}
static int combination(int my_input,int r) {
return factorial(my_input) / ( factorial(my_input-r) * factorial(r) );
}
public static void main(String args[]){
System.out.println();
int my_input, i, j;
my_input = 5;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the number of rows in Pascal's Triangle : ");
my_input = my_scanner.nextInt();
System.out.println("The Pascal's Triangle : ");
for(i = 0; i <= my_input; i++) {
for(j = 0; j <= my_input-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
System.out.print(" "+combination(i, j));
}
System.out.println();
}
}
}
输出
Required packages have been imported
A reader object has been defined
Enter the number of rows in Pascal's Triangle : 8
The Pascal's Triangle :
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
使用预定义输入
以下是打印星形帕斯卡三角形的步骤:
- 定义用于计算的阶乘和组合方法。
- 直接在代码中设置行数。
- 使用嵌套循环打印帕斯卡三角形,以使用预定义的行格式化和计算值。
示例
在这里,整数已预先定义,其值将在控制台上访问和显示:
public class PascalsTriangle {
static int factorial(int my_input) {
int factors;
for(factors = 1; my_input > 1; my_input--){
factors *= my_input;
}
return factors;
}
static int combination(int my_input,int r) {
return factorial(my_input) / ( factorial(my_input-r) * factorial(r) );
}
public static void main(String args[]){
System.out.println();
int my_input, i, j;
my_input = 8;
System.out.println("The number of rows in Pascal's Triangle is defined as " +my_input);
System.out.println("The Pascal's Triangle : ");
for(i = 0; i <= my_input; i++) {
for(j = 0; j <= my_input-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
System.out.print(" "+combination(i, j));
}
System.out.println();
}
}
}
输出
The number of rows in Pascal's Triangle is defined as 8
The Pascal's Triangle :
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP