计算一个变量值的平均值,android

时间:2015-04-19 07:56:13

标签: android eclipse

我有一个代码,根据用户的速度,每秒后生成一个值。现在我想要用户生成的所有速度值的平均值。我想在textview中显示它。

我该怎么做,有什么帮助?

这是我的代码:

LocationManager lm = (LocationManager) this
            .getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    this.onLocationChanged(null);

}

@Override
public void onLocationChanged(Location location) {
    TextView tv = (TextView) findViewById(R.id.textView1);

    if (location == null) {

        tv.setText("0.0");
    } else {

        nCurrentSpeed = location.getSpeed();
        tv.setText(nCurrentSpeed + "");

    }

现在这里nCurrentSpeed是每秒生成的值,我如何获得它生成的所有值并生成所有这些有争议的平均值。

3 个答案:

答案 0 :(得分:0)

一个解决方案:

average speed = total distance / total time 

所以,你只需要获得total distance

你持有一个变量来显示最后的location,称为 preLocation ,并保持一个变量来显示总距离,称为距离,然后尝试在onLocationChanged中添加代码:

distance += location.distanceTo(preLocation);
preLocation = location;
averageSpeed = distance / totalTime;

答案 1 :(得分:0)

为什么不在活动中添加2个变量?

private long startTime;
private float pointAverage;

在活动onCreate()方法中将这两个初始化。

现在,您可以修改代码

if (location == null) {
        startTime = System.currentTimeMillis();
        pointAverage = 0;
        actualizeTextField();
}

(这是你的开始吧?)

else {
        pointAverage += location.getSpeed();
        actualizeTextField();
}

最后添加类似这样的内容

    public void actualizeTextField() {
        TextView tf = (TextView) findViewById(R.id.textView1);

        if(count > 0) {
            long timeOver = System.currentTimeMillis() - startTime;
            tf.setText(String.valueOf(pointAverage/(timeOver/1000)));
        } else {
            tf.setText("0.0");
        }
    }

答案 2 :(得分:0)

  1. 录制录制开始时间timeStart并开始展示位置startLocation;
  2. 记录您当前的时间timeCurrent和当前位置currentLocation;
  3. 计算平均速度:

    //your spend time
    int spendTime = timeCurrent - timeStart;
    //the distance
    float distance = currentLocation.distanceTo(startLocation)
    //your average speed
    averageSpeed = distance / spendTime