gpt4 book ai didi

java - For 循环和数字的整除性

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:07 26 4
gpt4 key购买 nike

我已经学习 Java 大约一周了,最近几天一直在搞 for 循环。我使用了 if 语句来测试数字在多个属性上的整除性。以下是我到目前为止所得到的。

int g = 18;

if ((g % 2 )== 0 && (g % 3)== 0)
{
System.out.println("g is divisible by 2 and 3");
}
else
{
System.out.println("g is not divisible by 2 and 3");
}

if ((g % 7 )== 0 || (g % 9) == 0)
{
System.out.println("g is divisible by 7 or 9");
}
else
{
System.out.println("g is not divisible by 7 or 9");
}

if (((g % 2 )== 0) && ((g % 3) == 0) && ((g % 5) != 0))
{
System.out.println("g is divisible by 2 and 3 but 5");
}
else
{
System.out.println("g is not divisible by 2 and 3 but 5");
}

我正在尝试使用 for 循环来修改上面的每个程序,以便在每个程序的单次运行中测试 1 到 100 之间的所有数字。下面是我的 for 语句。

for(g=1;g<=100;++g)

问题是,我的程序根本无法运行。我完全理解错了吗?如果方向正确,我们将不胜感激。非常感谢。

最佳答案

试试这个:

public class Sample {

public static void main(String[] args) {

for (int g = 1; g <= 100; g++) {
if ((g % 2) == 0 && (g % 3) == 0) {
System.out.println(g + " is divisible by 2 and 3");
} else {
System.out.println(g + " is not divisible by 2 and 3");
}

if ((g % 7) == 0 || (g % 9) == 0) {
System.out.println(g + " is divisible by 7 or 9");
} else {
System.out.println(g + " is not divisible by 7 or 9");
}

if (((g % 2) == 0) && ((g % 3) == 0)) {
if ((g % 5) == 0) {
System.out.println(g + " is divisible by 2 and 3 and 5");
} else {
System.out.println(g + " is divisible by 2 and 3 but 5");
}
} else if ((g % 5) == 0) {
System.out.println(g + " is not divisible by 2 and 3 but 5");
} else {
System.out.println(g + " is not divisible by 2 and 3 and 5");
}
}
}
}

关于java - For 循环和数字的整除性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20373068/

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