gpt4 book ai didi

java - 在java中使用循环进行乘法显示不正确的答案

转载 作者:行者123 更新时间:2023-12-02 03:16:10 24 4
gpt4 key购买 nike

我尝试分别使用 for 、 while 和 do-while 循环来计算 5*10*15*...50 。当我运行代码时,它显示错误答案,等于 0。我无法找出代码中的问题。有人可以帮我看一下吗??非常感谢~~下面是我的代码:

public class Main {

public static void main(String[] args) {


ForMethod show1 = new ForMethod();
show1.computeForLoop();
System.out.println();

DWMethod show2 = new DWMethod();
show2.computeDWLoop();
System.out.println();

WhileMethod show3 = new WhileMethod();
show3.computeWhileLoop();

}

}


// For Loop
public class ForMethod {

long mul;

public void computeForLoop(){

System.out.println("Compute using For Loop : ");
for(int x = 1; x <= 10 ; x++){

if ( x < 10){

System.out.print(x*5 + " x ");

} else { System.out.print(x*5);}

mul *= x*5;
}

System.out.println("\nThe Product of Number = " + mul);

}
}


// While Loop Method
public class WhileMethod {

int x = 1 ;
long mul;

public void computeWhileLoop(){

System.out.println("Compute using While Loop : ");

while(x < 10){

System.out.print(x*5 + " x ");
x++;


if (x == 10){

System.out.print(x*5);
}

mul *= (x*5);
}

System.out.println();
System.out.println("The Product of Number = " + mul);
}


}


// Do-While Loop Method
public class DWMethod {

int x = 1;
long mul;

public void computeDWLoop(){

System.out.println("Compute using Do-While Loop : ");

do{

if (x < 10 ){

System.out.print(x*5 + " x ");

} else

if (x == 10){

System.out.print(x*5);
}

mul *= x;
x++;

} while (x <= 10);


System.out.println();
System.out.println("The Product of Number = " + mul);

}
}

最佳答案

问题是您的 mul 字段已初始化为零。这意味着您总是乘以零。

关于java - 在java中使用循环进行乘法显示不正确的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40264704/

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