我需要为 n 个数字做一个“1,-1,2,-2,3,-3 ...”的序列,我已经编写了代码,并且它有效,但我不知道这是否是正确的方法去做吧 Scanner teclado = new Scanner(System.in); System.out.println("Ingresa el numero N"); int n = teclado.nextInt(); int r = 0; for (int i = 1; i <= n; i++) { if (i >= 0) { r = i * 1; } if (r >= 0) { r = i * -1; } System.out.print(i+","+r+","); }
1 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
您可以通过使用单个计数器和循环来改进当前代码:
Scanner teclado = new Scanner(System.in);
System.out.println("Ingresa el numero N");
int n = teclado.nextInt();
for (int i=1; i <= n; ++i) {
if (i > 1) System.out.print(",");
System.out.print(i + "," + (-i));
}
这打印,为n=3:
1,-1,2,-2,3,-3
添加回答
举报
0/150
提交
取消