【发布时间】:2015-03-09 12:50:50
【问题描述】:
我正在尝试编写一个打印出由数字组成的三角形的程序。它应该是这样的:
1
2 3 4
3 4 5 6 7
4 5 6 7 8 9 0
5 6 7 8 9 0 1 2 3
6 7 8 9 0 1 2 3 4 5 6
在我的例子中,它返回负数 (876543210-1-2-3...) 但它应该只使用 0-9。我可以使用模 n%10,但我不知道该怎么写。有什么帮助吗?谢谢。
import java.util.Scanner ;
public class Triangle {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number: ");
int n = sc.nextInt();
int j;
int i;
int k = n-1;
System.out.printf("n=%d\n\n", n);
for (i=1; i<=(n*2); i=i+2) {
for (j=0; j<=2*n-1; j++) {
if (j < k){
System.out.print(" ");
}
else if (j < (k+i)){
System.out.printf("%d", (n-j));
}
else {
System.out.print(" ");
}
}
k = k-1;
System.out.println();
}
}
}
【问题讨论】:
-
使用 n%10 只是意味着如果 n 介于 0 和 9 之间,它将给出 n,但是当它大于 10 时,它将是:10 到 0、11 到 1、12,到 2、13 到 3 ......据我所知,基本上正是你想要的
-
关于负数的快速“修复”可能是
System.out.printf("%d", Math.abs(n-j));而不是System.out.printf("%d", (n-j));,但这表明问题比负数更多。