簡體   English   中英

如何在while循環中添加距離?

[英]How do I add the distances in a while loop?

我應該在N步之后加上步行者位置的距離。 我運行了一段時間的T次,需要在T步之后添加所有N個步驟,然后除以嘗試次數即可得出平均值。 到目前為止,這是我的代碼。 iv嘗試做一個不同的整數,例如distance / 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 = ");

我認為這是因為您沒有跟蹤總距離。 另外,您的distance int變量僅存在於范圍內:

        if (N==x)
        {
            int distance=(stepsX*stepsX)+(stepsY*stepsY);
            System.out.println(distance);
        }

在此處閱讀有關范圍的更多信息: do-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;
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) );

這將是我的答案,您似乎正在失去所有步驟,除了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);

但是請不要重新表達您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM