【发布时间】:2019-05-27 21:57:01
【问题描述】:
我正在开发用户选择一个正整数的冰雹序列程序。如果数字是偶数,它将被除以二。如果数字是奇数,则将其乘以三并加一。程序将继续执行,直到数字等于 1。程序还将告诉用户达到 1 所需的步数。
目标是递归完成,我的问题是我无法向用户声明每个步骤,因为计算发生在数字上,例如“数字是所以我除以 2 并且它 =”
这是我目前的代码,任何建议或替代方案都会有所帮助。
谢谢
import javax.swing*
{
public class hailstone {
static int Count;
static int HailstoneNumbers(int Num)
output += (Num + " " ) ;
JOptionPane.showMessageDialog(null, output);
if (Num == 1 && Count == 0) {
return Count;
}
else if (Num == 1 && Count != 0) {
//n-1
Count++;
return Count;
}
else if (Num % 2 == 0) {
Count++;
HailstoneNumbers(Num / 2);
}
else if (Num % 2 != 0) {
Count++;
HailstoneNumbers(3 * Num + 1);
}
return Count;
}
public static void main(String[] args)
{
int Num = Integer.parseInt(JOptionPane.showInputDialog("\n Enter a positive number"));
int x;
x = HailstoneNumbers(Num);
JOptionPane.showMessageDialog(null, "Number of Steps" + x );
}
}
【问题讨论】:
标签: java