英文:
I am having trouble printing out the right output of numbers for this Data Structure using a for loop and a while loop
问题
使用for循环进行printCount(),使用while循环进行printWhileCount(),如果正在添加的数字n可被2整除,则输出为数字的1/2加n,如果可被3整除,则输出为0,否则输出为数字。
printCount()函数和printWhileCount()的输出应为:
5 1 6 0 7 5 8 7 9 0,
5 1 6 0 7 5 8 7 9 0
而实际输出是:
10 8 12 9 0 10 16 11 18 12,
10 8 12 9 0 10 16 11 18 12
这是我的代码:
public class HelloPrinter {
public static void main(String[] args) {
printCount(5);
printCountWhile(5);
}
public static void printCount(int n) {
for (int i = 0; i < 10; i++) {
int num = i + n;
if (num % 2 == 0) {
System.out.print((num / 2) + n + " ");
} else if (num % 3 == 0) {
System.out.print("0 ");
} else {
System.out.print(num + " ");
}
}
System.out.println();
}
public static void printCountWhile(int n) {
int i = 0;
while (i < 10) {
int num = i + n;
if (num % 2 == 0) {
System.out.print((num / 2) + n + " ");
} else if (num % 3 == 0) {
System.out.print("0 ");
} else {
System.out.print(num + " ");
}
i++;
}
System.out.println();
}
}
我似乎无法弄清楚我做错了什么。
英文:
using a for loop for printCount() and whileLoop for printWhileCount() if the number n is being added to is divisible by 2, the output is 1/2 the number plus n, if it's divisible by 3, the output is 0, and if it's anything else, the output is the number.
the printCount() function and the
printWhileCount()output should be
5 1 6 0 7 5 8 7 9 0,
5 1 6 0 7 5 8 7 9 0
instead the output is
10 8 12 9 0 10 16 11 18 12,
10 8 12 9 0 10 16 11 18 12
This is my code
public class HelloPrinter {
public static void main(String[] args) {
printCount(5);
printCountWhile(5);
}
public static void printCount(int n) {
for (int i = 0; i < 10; i++) {
int num = i + n;
if (num % 2 == 0) {
System.out.print((num / 2) + n + " ");
} else if (num % 3 == 0) {
System.out.print("0 ");
} else {
System.out.print(num + n + " ");
}
}
System.out.println();
}
public static void printCountWhile(int n) {
int i = 0;
while (i < 10) {
int num = i + n;
if (num % 2 == 0) {
System.out.print((num / 2) + n + " ");
} else if (num % 3 == 0) {
System.out.print("0 ");
} else {
System.out.print(num + n + " ");
}
i++;
}
System.out.println();
}
}
I can't seem to figure out what I am doing wrong
答案1
得分: 1
The corrected description should then be:
如果索引可以被2整除,输出为1/2的索引加n;如果可以被3整除,输出为0;否则输出索引本身。
英文:
The description you give does not correspond to the desired output. I guess you should not calculate num
, but should apply the logic to i
:
if (i % 2 == 0) {
System.out.print((i / 2) + n + " ");
} else if (i % 3 == 0) {
System.out.print("0 ");
} else {
System.out.print(i + " ");
}
The corrected description should then be:
> if the <strike>number n is being added to</strike> index is divisible by 2, the output is 1/2 the <strike>number</strike> index plus n, if it's divisible by 3, the output is 0, and if it's anything else, the output is the <strike>number</strike> index.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论