【发布时间】:2013-10-22 02:54:01
【问题描述】:
今天我正在研究一种将刻度线放置在标尺上的递归方法。作业说放置刻度线并打印它的高度和位置。假设 x & y 为 (0,0),宽度为 20,高度为 10,程序应该显示类似
中间刻度线 - 位置 10,高度 10
位置 5,高度 5
位置 2.5,高度 2.5
位置 7.5,高度 2.5
位置 15.0,高度 5.0
位置 12.5,高度 2.5
位置 17.5,高度 2.5
请注意,允许的最小高度是 2.00,每个位置都是较大位置高度的一半。我尝试了很多东西,我有点想法,但没有奏效。我得到了从位置 10 到 7.5 的数字,但是即使只是移动 x 坐标,右侧也是一团糟。这是我的代码,希望你能帮助我,谢谢。
*main method contains the input for user and the method calls.
DrawRulerLeft(x,y,width,height); //Method to draw left part of rule
DrawRulerRight(x,y,width,height); //Method to draw right part of rule
public static void DrawRulerLeft(double x, double y, double w, double h) {
if (h > 2 ) { //smallest height aloud
w = w/2;
System.out.println("Tick position:+ w + " Tick height: " + h );
DrawRulerLeft(x, y, w, h/2);
}
}
//Recursive method to draw right of rule
public static void DrawRulerRight(double x, double y, double w, double h) {
if (h > 2 && w >= 0) {
DrawRulerRight(x+w/2,y,w/2,h/2);
System.out.println("Tick position:" + x + " Tick height: " + h );
}
}
【问题讨论】:
-
我没有测试过您的代码,但知道您需要在这两种方法中调用这两种方法。换句话说,
drawRulerLeft(...)需要同时调用drawRulerLeft(...)和drawRulerRight(...),drawRulerRight(...)也是如此。另请注意,方法名称应以小写字母开头,并且代码格式很重要,不应视为理所当然(正如您所做的那样)。 -
有左右方法的原因不清楚。为什么一个递归函数不能同时处理这两个子问题
-
@clwhisk:好点。
-
@clwhisk 是的,我实际上想过只使用一个递归函数,但我不知道,当我尝试它时弄得一团糟,所以我决定改为创建两种方法
-
用一个,在你这样做的时候请不要忽略代码格式。如果不是,它会导致你搞砸,或者如果不是这样,会让你要求帮助你的人感到沮丧。