西安交通大学JAVA课程题目实践----输出字符图形

it2024-10-24  35

标题输出以下字符图形,比如,当n=6时,结果如下图1;当n=5时,结果如下图2。

1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 6 6 图1   1 2 2 2 3 3 3 3 3 4 4 4 4 5 5 图2

代码如下:

import java.util.Scanner; public class Demo5 { /** * @kilimy * */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入正整数n"); double n = (double)sc.nextInt(); System.out.println("输出图像"); //上半层循环与中间层 for (int i = 1; i <= Math.ceil(n / 2); i++) { System.out.printf("%" + (n - i) * 2 + "s", ""); for (int j = 1; j <= 2 * i - 1; j += 1) { System.out.format("%2d", 2 * i - 1); } System.out.println(""); }int num=(int)Math.floor(n/2)*2; //下半层循环 for (int i = 1; i <= Math.floor(n / 2); i++) { System.out.printf("%" + (2*(n - Math.ceil(num / 2))-1)+ "s", ""); for (int j = 1; j <= Math.floor(num/ 2)*2; j++) { System.out.format("%2d", num); } num -=2; System.out.println(""); } } } /** * 输出结果: ========================== 偶数 请输入正整数n 6 输出图像 1 3 3 3 5 5 5 5 5 6 6 6 6 6 6 4 4 4 4 2 2 =========================== 奇数 请输入正整数n 7 输出图像 1 3 3 3 5 5 5 5 5 7 7 7 7 7 7 7 6 6 6 6 6 6 4 4 4 4 2 2 */
最新回复(0)