gpt4 book ai didi

java - 递归方法 - 标尺刻度线

转载 作者:行者123 更新时间:2023-11-29 03:28:51 24 4
gpt4 key购买 nike

今天我正在使用递归方法在标尺上放置刻度线。作业要求放置刻度线并打印其高度和位置。假设 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 );
}

}

最佳答案

基本上,您只需要考虑到任何时候存在标尺的除法时,就会同时存在 + 和 - 排列。忽略标尺范式的左侧/右侧,因为每个分区只有左侧/右侧。

drawTicks(20, 20, 20);

public static void drawTicks(double h, double tick, double pos) {

System.out.println("tick: " + tick + " pos: " + pos);

if (tick / 2 >= 2) {

if (tick != h) {
drawTicks(h, tick / 2, pos + tick / 2);
}

drawTicks(h, tick / 2, pos - tick / 2);
}

}

输出如下:

tick: 20.0 pos: 20.0
tick: 10.0 pos: 10.0
tick: 5.0 pos: 15.0
tick: 2.5 pos: 17.5
tick: 2.5 pos: 12.5
tick: 5.0 pos: 5.0
tick: 2.5 pos: 7.5
tick: 2.5 pos: 2.5

关于java - 递归方法 - 标尺刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19508217/

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