我应该在N步之后添加助行者位置的距离。我运行了T次,需要在T轨迹之后添加所有N个步骤并除以试验数量以获得平均值。到目前为止这是我的代码。我尝试做一个不同的整数,如距离/ T,但它说没有找到距离。是因为它是在while循环中定义的。我正在使用处理。
import javax.swing.JOptionPane;
String input=JOptionPane.showInputDialog("Steps");
int x=Integer.parseInt(input);
if (x<0)
{
System.out.println("Error. Invalid Entry.");
}
int T=1;
int N=0;
while (T<10)
{
while (N<x)
{
int stepsX=Math.round(random(1,10));
int stepsY=Math.round(random(1,10));
System.out.println(stepsX+","+stepsY);
N=N+1;
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
System.out.println(distance);
}
}
T=T+1;
N=0;
}
System.out.println("mean sq. dist = ");
答案 0 :(得分:1)
我假设是因为你没有跟踪总距离。此外,您的distance
int变量仅存在于范围中:
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
System.out.println(distance);
}
在此处详细了解范围:Scope of do-while loop?
有点不清楚你需要什么,但我做的一些改变我认为会有所帮助:
import javax.swing.JOptionPane;
String input=JOptionPane.showInputDialog("Steps");
int x=Integer.parseInt(input);
if (x<0)
{
System.out.println("Error. Invalid Entry.");
}
int T=1;
int N=0;
double totalDistance = 0.0;//keep track over over distance;
while (T<10)
{
while (N<x)
{
int stepsX=Math.round(random(1,10));
int stepsY=Math.round(random(1,10));
System.out.println(stepsX+","+stepsY);
N=N+1;
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
totalDistance = totalDistance + distance;
System.out.println("current distance: " + distance);
System.out.println("current total distance: " + totalDistance);
}
}
T=T+1;
N=0;
}
//calculate whatever you need using totalDistance
System.out.println("mean sq. dist = " + (totalDistance/T) );
答案 1 :(得分:0)
这将是我的答案,你好像失去了所有的步骤,除了在while循环中的最后一步。
import javax.swing.JOptionPane;
String input=JOptionPane.showInputDialog("Steps");
int x=Integer.parseInt(input);
if (x<0)
{
System.out.println("Error. Invalid Entry.");
}
int T=1;
int N=0;
int stepsX = 0;
int stepsY = 0;
while (T<10)
{
while (N<x)
{
stepsX += Math.round(random(1,10));
stepsY += Math.round(random(1,10));
System.out.println(stepsX+","+stepsY);
N=N+1;
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
System.out.println(distance);
}
}
T=T+1;
N=0;
}
double distance = Math.sqrt(Math.pow(stepsX, 2) + Math.pow(stepsY, 2));
System.out.println("mean sq. dist = "+distance);
但请不要重述你的问题。