gpt4 book ai didi

java - 打印数字 1-100,除非能被 5 或 12 整除

转载 作者:行者123 更新时间:2023-11-29 08:32:07 25 4
gpt4 key购买 nike

问题是

Write a Java program that prints numbers from 1 to 100. If the number is divisible by 5, instead of printing the number, your program should print how many fives are in this number, if the number is divisible by 12 it should print how many twelves are in this number.

这是我目前的尝试:

import acm.program.*;

public class FiveTwelve extends ConsoleProgram {
public void run() {
int a = (1);
int b = (5);
int c = (12);
for (a = 1; a <= 100; a++) {
println(a);
if ((a % 5) == 0) {
println(a/b);
} else if ((a % 12) == 0) {
println(a / c);
}
}
}
}

问题是我的代码还打印了可整除的数字,而不仅仅是结果。示例输出:

1
2
3
4
5
1
6
7
8
9
10
2
11
12
1

继续下去。我想删除可被 5 和 12 整除的数字。相反,我需要显示结果或 num/5 && num/12。

更新!!!

import acm.program.*;
public class FiveTwelve Extends ConsoleProgram{
public void run() {
for (int a = 1; a <= 100; a++) {
if (a % 5 == 0 && a % 12 == 0) {
println(a / 5);
println(a / 12);
} else if (a % 5 == 0) {
println(a / 5);
} else if (a % 12 == 0) {
println(a / 12);

} else {
println(a);
}
}
}
}

我猜我们都错过了什么。

最佳答案

让我们编写一个可扩展的解决方案,而不是解决特定情况。首先,问题中有哪些变量可以改变?我会说他们是:

  1. 起始编号1
  2. 最后一个数字100
  3. 除数 512

此外,正如@Anoml 指出的那样,问题措辞表明,如果您的数字可以被多个除数整除,我们应该打印出它被每个 适用除数整除的次数。而且,正如您在问题中指出的那样,我们只想打印不能被任何除数整除的数字本身。

因此,我们的解决方案变为:

import acm.program.*;

public class FiveTwelve extends ConsoleProgram {
private final int FIRST = 1;
private final int LAST = 100;
private final int[] DIVISORS = { 5, 12 };

public void run() {
boolean hasDivisor;

for (int i = FIRST; i <= LAST; i++) {
hasDivisor = false;

for (int divisor : DIVISORS) {
if (i % divisor == 0) {
println(i / divisor);
hasDivisor = true;
}
}

if (!hasDivisor) {
println(i);
}
}
}
}

这样,我们可以更改起始编号、最后编号或我们支持的除数,程序仍然会通过。

关于java - 打印数字 1-100,除非能被 5 或 12 整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042865/

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