java - 如何确定用于确定弗洛伊德三角形的 Java 循环数组中第一个数字的公式?
问题描述
嗨所以我有java循环问题。
所以我试图弄清楚如何通过输入三角形的高度来确定弗洛伊德三角形循环中的第一个数字(在模式的顶部)。
注意:只输入高度来确定第一个数字,最后一个数字应固定为1。
例如:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
另一个是
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
我已经弄清楚了如何进行模式和值的递减,但我似乎无法弄清楚第一个数字。我一直在试图弄清楚这个序列,但它仍然让我感到困惑,因为我还是 java 新手。
这是我的代码:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
代码仍未完成,因为我无法弄清楚公式:(
我会很感激我能找到的任何帮助。谢谢!
解决方案
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
还可以看看System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
输出
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
推荐阅读
- java - Java 日历中的前一天不正确
- perl - how do parsing DynamicWebsite data
- postgresql - ALTERING MULTIPLE TABLES IN POSTGRES
- autohotkey - 在循环中无法执行任何其他操作
- sql - 如何使用 SQL 获取特定字符串值下的行
- instagram - Instagram API:如何获得 1440 像素?
- c# - 正则表达式非捕获组捕获
- swift - 如何处理返回值的函数的错误
- php - 使用 PHP 和 MySQL 创建动态列表
- python - 如果我从函数中更改 Python 全局变量的数据,则会引发错误。(如果不传递任何参数,它工作正常)