gpt4 book ai didi

java - 使用 Java - 每 9 个字符宽行打印四次迭代

转载 作者:行者123 更新时间:2023-12-02 11:21:03 24 4
gpt4 key购买 nike

// Write a program that uses a while loop to detect and print multiples of 13 or 17, but not both. Use the exclusive or operator as on page 93. 
// The program should start examining integers at 200, and examine successively larger integers until 16 multiples have been detected.
// Correct multiples should be printed right aligned in fields that are 9 characters wide, but with only four multiples per line.
// The total of all correct multiples should be reported after all 16 multiples have been printed.

package Programs5;

public class Program51 {

public static void main(String[] args) {
int main = 200, x = 0, y = 13, z = 17;
while(x < 16) {
main += 1;
if(main % y == 0 ^ main % z == 0) {
x += 1;
System.out.print(main + " ");
}
}
}

}

当我运行程序时,逻辑工作并正确打印每个倍数。但是我需要每行打印四次迭代。例如:

x x x x

我很难弄清楚这个问题。根据我在 Python 方面的一点经验,我假设我需要一个循环,但此时我迷失了方向。

最佳答案

您忘记将字段对齐到九个字符宽的列中(我会使用 printf,并在 count 是四的倍数时简单地添加换行符)。我首先将模运算的结果保存在局部变量中。此外,您还需要保留总计。比如,

int count = 0, total = 0, start = 200;
for (; count < 16; start++) {
boolean mod13 = start % 13 == 0, mod17 = start % 17 == 0;
if (mod13 ^ mod17) {
if (count > 0) {
if (count % 4 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
total += start;
System.out.printf("% 9d", start);
count++;
}
}
System.out.printf("%nTotal = %d%n", total);

输出

      204       208       234       238
247 255 260 272
273 286 289 299
306 312 323 325
Total = 4331

关于java - 使用 Java - 每 9 个字符宽行打印四次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60045523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com