有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java以倒置的直角打印奇数

我试着取一个数字,然后打印出来,它是奇数,如下所示:

    if i take 5 as a number it should give this: 

    1 3 5
    3 5
    5

   and if i take 9 it should do the same thing:

  1 3 5 7 9
  3 5 7 9
  5 7 9
  7 9
  9

这就是我到目前为止所拥有的,我被困住了。我无法让5在3之后打印,并以5结束三角形:

public class first{
    static void afficher(int a){
    for(int i=1;i<=a;i++){
        if(i%2!=0){
            System.out.printf("%d",i);
        }
    }
    System.out.println();

    for(int j=3;j<=a-2;j++){
        if(j%2!=0){
            System.out.printf("%d",j);
        }
    }
}




     public static void main(String[]args){
        afficher(5);


    }

}

这张照片是:

1 3 5
3

共 (3) 个答案

  1. # 1 楼答案

    必须使用嵌套for循环来解决此问题。检查下面的代码

    public class OddNumberLoop {
    
     public static void main(String[] args) {
    
        Scanner inpupt = new Scanner(System.in);
    
        System.out.print("Input the starting number : ");
        int start = inpupt.nextInt();
        for(int i = 1 ; i <= start; i += 2){
            for(int x = i; x <= start; x += 2) System.out.print(x+ " ");
            System.out.println();
        }
    
     }
    }
    
  2. # 2 楼答案

    打印的原因如下:

    1 3 5 -> your i loop runs here (from 1 to 5)
    3     -> your j loop runs here (from 3 to (less than OR equal to 5))
    

    因此,我建议如下:

    1. 使用2个嵌套循环(用于通用值):

       i running from 1 to the input number increasing by 2
       j running from i to the input number increasing by 2 also ending with line change'/n'  
      
    2. 检查输入的数字是否为奇数

  3. # 3 楼答案

    如果你打印一个曲面(因此是2d),人们期望算法在O(n^2)时间复杂度下运行。因此,两个嵌套的for

    public class first{
        static void afficher(int a){
            for(int i = 1; i <= a; i += 2) {
                for(int j = i; j <= a; j += 2){
                    System.out.print(j);
                    System.out.print(' ');
                }
                System.out.println();
            }
        }
    }
    

    通过不检查if这个数字是奇数,而是采取2的步骤,可以稍微优化算法

    demo