gpt4 book ai didi

java - 能被5或6整除

转载 作者:行者123 更新时间:2023-12-01 06:28:37 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,其中列出 100-1000 之间可被 5 或 6 整除的所有数字。这是我使用的代码:

public class divisibleBy5and6 {
public static void main (String[] args) {

j = 1;
int number = 100;
while (number < 1001) {
if (number % 6 == 0 || number % 5 == 0) {
System.out.print(number + ", ");
number++;
j++; }

if (j % 10 == 0 && j != 0) {
System.out.println();
j++; }
else {
number++;
}
}

我使用 int j 来制作它,因此每行有 9 个。这是我的输出:

100, 102, 105, 108, 110, 114, 120, 125, 130, 
132, 135, 138, 140, 144, 150, 155, 160, 162,
165, 168, 170, 174, 180, 185, 190, 192, 195,
198, 200, 204, 210, 215, 220, 222, 225, 228,
230, 234, 240, 245, 250, 252, 255, 258, 260,
264, 270, 275, 280, 282, 285, 288, 290, 294,
295, 300, 305, 310, 312, 315, 318, 320, 324,
325, 330, 335, 340, 342, 345, 348, 350, 354,
355, 360, 365, 370, 372, 375, 378, 380, 384,
385, 390, 395, 400, 402, 405, 408, 410, 414,
415, 420, 425, 430, 432, 435, 438, 440, 444,
445, 450, 455, 460, 462, 465, 468, 470, 474,
475, 480, 485, 490, 492, 495, 498, 500, 504,
505, 510, 515, 520, 522, 525, 528, 530, 534,
535, 540, 545, 550, 552, 555, 558, 560, 564,
565, 570, 575, 580, 582, 585, 588, 590, 594,
595, 600, 605, 610, 612, 615, 618, 620, 624,
625, 630, 635, 640, 642, 645, 648, 650, 654,
655, 660, 665, 670, 672, 675, 678, 680, 684,
685, 690, 695, 700, 702, 705, 708, 710, 714,
715, 720, 725, 730, 732, 735, 738, 740, 744,
745, 750, 755, 760, 762, 765, 768, 770, 774,
775, 780, 785, 790, 792, 795, 798, 800, 804,
805, 810, 815, 820, 822, 825, 828, 830, 834,
835, 840, 845, 850, 852, 855, 858, 860, 864,
865, 870, 875, 880, 882, 885, 888, 890, 894,
895, 900, 905, 910, 912, 915, 918, 920, 924,
925, 930, 935, 940, 942, 945, 948, 950, 954,
955, 960, 965, 970, 972, 975, 978, 980, 984,
985, 990, 995, 1000,

这显然是不对的,因为我缺少像 115 这样的数字。我做错了什么?

最佳答案

您需要将数字增量与 if/else 语句分开。无论如何,它应该在每次迭代中发生......

int j = 1; 
int number = 100;
while (number < 1001) {
if (number % 6 == 0 || number % 5 == 0) {
System.out.print(number + ", ");
j++;
}
if (j % 10 == 0) {
System.out.println();
}
number++;
}

关于java - 能被5或6整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017206/

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