如何确定Java';中确定第一个数字的公式;用于floyd'的s循环阵列;s三角形?

如何确定Java';中确定第一个数字的公式;用于floyd'的s循环阵列;s三角形?,java,loops,for-loop,while-loop,Java,Loops,For Loop,While Loop,嗨,我有java循环问题 因此,我试图通过输入三角形的高度来确定floyd三角形循环中的第一个数字(在图案顶部) 注:仅输入高度以确定第一个数字,最后一个数字应固定为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 1

嗨,我有java循环问题

因此,我试图通过输入三角形的高度来确定floyd三角形循环中的第一个数字(在图案顶部)

注:仅输入高度以确定第一个数字,最后一个数字应固定为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();
        }


    }
}
import java.util.Scanner;
公共班机
{
公共静态void main(字符串[]args){
int n;
整数起始数=;
扫描仪输入=新扫描仪(System.in);
System.out.print(“输入三角形的高度:”);
n=input.nextInt();
系统输出打印(“第一个数字是”+起始数字);

对于(int i=1;i你解决这类问题的方法是通过找到一个数学关系。在这种情况下,你知道(当输入为6)高度为6。你还知道,在每一行,你的数字比后面的少一个。底部的数字为6,因为它与高度相同

因此,您需要执行6+5+4+3+2+1来获得起始编号

现在,这是一个通用的解决方案:n+(n-1)+((n-1)-1)…+1

这方面的一个可能实施方案是:

System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;

这道数学题是,这是一道

我也来看看


它成功了!但是你是怎么算出这个公式的呢?我在过去的3个小时里一直在试图解决这个问题,但你马上就解决了。有没有办法让我得到这样的数学公式呢?@Brian通常你从基本的例子开始
S1=1
S2=1+2
,然后尝试推导出一个通用公式
Sn=1+2+2+..+n
n*(n+1)/2
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n

=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
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