【发布时间】:2015-09-05 22:21:12
【问题描述】:
我正在学习java。我怀疑我的compute_Hailstone_Sequence 方法在遇到返回语句时终止。有了begin_num = 7 和steps = 10 的两个输入,我的理想输出应该代表7 22 11 34 17 52 26 13 40 20 我还怀疑我还没有增加x,因为我的代码确实会产生前两个值7 22 ..我不确定还可以产生一个累积算法。我知道使用数据结构的答案,但我试图在不使用列表或数组或任何其他数据结构的情况下对此进行编码。这不是家庭作业。
import java.util.Scanner;
/**
* Created on 9/5/15.
* Following Reges, Stuart, and Martin Stepp. Building Java Programs: A Back to Basics Approach. 3rd Edition.
* Chapter 4
*/
public class Ch4 {
public static void main(String[] args) {
hailstone_Sequence();
}
public static void hailstone_Sequence(){
giveIntro();
Scanner user_console = new Scanner(System.in);
System.out.println("Please provide a starting integer: ");
int BEGINVALUE = user_console.nextInt();
// System.out.println("Please provide an ending integer: ");
// int ENDVALUE = user_console.nextInt();
System.out.println("Thank you. How long would you liked the sequence to be?");
int STEPS = user_console.nextInt();
System.out.println("Calculating..");
compute_Hailstone_Sequence(BEGINVALUE, STEPS);
}
public static int compute_Hailstone_Sequence(int begin_num, int steps){
System.out.print(begin_num + " ");
for (int i = 1; i <= steps; i++ ){
int x;
if ((begin_num & 1) == 0 ){
// even
// int x = 0;
x = (begin_num / 2);
System.out.print(x + " ");
// return x;
}
else {
// int x = 0;
x = (3 * begin_num + 1);
System.out.print(x + " ");
// return x;
}
return x;
}
return begin_num;
}
}
【问题讨论】:
-
(begin_num & 1) 这是什么???但是,进一步解释了这个问题,然后函数 compute_Hailstone_Sequence() 返回一个整数..我看到整个分配的服务.. ??我不认为..
-
@MicheleLacorte stackoverflow.com/questions/7342237/…
-
我已经添加答案检查它@phillipsK
标签: java