gpt4 book ai didi

Java-桥上的人

转载 作者:行者123 更新时间:2023-12-04 05:25:20 24 4
gpt4 key购买 nike

这个问题不太可能对任何 future 的访客有帮助;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,通常不适用于互联网的全局受众。如需帮助使这个问题更广泛地适用,visit the help center .




8年前关闭。




我在一个程序中遇到问题,其中一个人从 7 英尺的桥中间开始。这是描述:

Someone is standing at the center of a bridge that is 7 ft bridge long. Their stride is exactly one foot. They can’t control the direction they are going but the bridge is very narrow and they can only go forward or backward with each step.

Write a program that calculates how many steps the person will walk before exiting the bridge. Have the program execute this simulation 1000 times and as your output display the average and greatest number of steps taken. (Hint: generate a random number that is either 0 or 1 and let one equal forward and the other backward). Do this 20 times so that you can make comparative observations.



这是我到目前为止:
import java.util.Random;
import java.util.Scanner;
import java.text.DecimalFormat;

public class prog214a
{
public static void main(String[] args)
{
Random generator = new Random();
System.out.println("1000 iterations");
int runs = 0;
int iter = 1000;
double count = 7.0 / 2.0;
int random;
System.out.println("Run\tAvarage\tGreatest Number of Steps");
// for(runs=1;runs<20; runs+=1)
// {
for (iter = 1000; iter > 1; iter -= 1)
{
double tries = 1;
double avg = count / tries;
random = generator.nextInt(2);
if (random == 0)
{
count -= 1;
}
if (random == 1)
{
count += 1;
}
if (count <= 0 || count >= 7)
{
System.out.println("#" + runs + ":\t" + avg + "\t" + count);
count = 0;
runs += 1;
}
tries += 1;
}
// }
}
}

最佳答案

你的部分问题在于你处理它的方式。您的代码应该显示从您正在做的抽象事情到实际机械执行的简洁路径。

你的第一个问题是建立一个算法,或者你想要发生的事件序列:

Print out position
Decide direction
Move
Repeat n times

现在让我们将这些粗略的步骤转化为代码。我们通过为每个方法创建方法来做到这一点:
public void printPosition();
public int findDirectionVector();
public void updatePosition(int move);//move is a vector
public void runSimulation(int iterations);

现在让我们填写控制方法:
public void runSimulation(int iterations) {
for (n = 0; n < iterations ; n++) {
executeIteration();//simple!
}
}

private void executeIteration() {
printPosition();
updatePosition(findDirectionVector());
}

如您所见,我们正在确保 每种方法只做一件事 .我们还将某些东西(例如 Position)作为类的成员变量,而不是尝试将其作为您正在传递的变量来处理。然而,这是一个变化,所以让我们看看你的初始化和类结构:
public Simulation {
private int position = 0;
private int iterations = 0;//number of times the person moves before you stop!

public Simulation(int iterations) {
this.iterations = iterations;
}

public static void main(String[] args) {
Simulation sim = new Simulation(1000);//Run with 1000 iterations
sim.runSimulation();
}

//your other methods go here
}

现在,当你想运行 1000 次时,你只需要包装 sim.runSimulation()在 for 循环中。

我遗漏了一项非常重要的检查(此人是否已离开桥?)以及其他方法的实现供您执行。

关于Java-桥上的人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262072/

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