gpt4 book ai didi

java - 我无法以正确的顺序获取整数

转载 作者:行者123 更新时间:2023-11-30 06:48:27 25 4
gpt4 key购买 nike

我有部分代码询问数字,但我无法按我需要的正确顺序获取它们。我也不确定如何将它们相加并显示它们的数量。

Problem Statement:

Program that uses one loop to process the integers from 300 down to 200, inclusive. The program should detect multiples of 11 or 13, but not both. The multiples should be printed left-aligned in columns 8 characters wide, 5 multiples per line. When all multiples have been displayed, the program should display the number of multiples found and their sum.

package chapter5;

public class Assignment1 {

public static void main(String[] args) {
int sum = 300;
while (sum >= 200 && sum <= 300 ) {
if((sum % 11 == 0) != (sum % 13 == 0)) {
System.out.print(sum + " ");
}
sum = sum - 1;
}
}
}

输出:

299 297 275 273 264 260 253 247 242 234 231 221 220 209 208

最佳答案

首先,您可以从 List<Integer> 开始收集您的倍数。遍历你得到的值。测试每个值是否是 11 xor 13 的倍数。如果是,将它添加到一个求和变量中,然后添加到您的 List 中。 .然后迭代List , 左对齐打印每个值并每第五行添加一个换行符。然后显示计数(List 的大小)和 sum .类似的东西,

int sum = 0;
List<Integer> al = new ArrayList<>();
for (int i = 300; i >= 200; i--) {
if ((i % 11 == 0) ^ (i % 13) == 0) {
al.add(i);
sum += i;
}
}
for (int i = 0; i < al.size(); i++) {
System.out.printf("%-8d", al.get(i));
if ((i + 1) % 5 == 0) {
System.out.println();
}
}
System.out.printf("Found %d multiples, with a sum of %d.%n", al.size(), sum);

哪些输出

299     297     275     273     264     
260 253 247 242 234
231 221 220 209 208
Found 15 multiples, with a sum of 3733.

一个循环,没有List喜欢,

int sum = 0;
int count = 0;
for (int i = 300; i >= 200; i--) {
if ((i % 11 == 0) ^ (i % 13) == 0) {
System.out.printf("%-8d", i);
count++;
sum += i;
if (count % 5 == 0) {
System.out.println();
}
}
}
System.out.printf("Found %d multiples, with a sum of %d.%n", count, sum);

对于相同的输出。

关于java - 我无法以正确的顺序获取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44253160/

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