【问题标题】:How to calculate distance travelled from speed and time (not from location points) :Android(Java)如何从速度和时间(不是从位置点)计算行驶距离:Android(Java)
【发布时间】:2021-07-17 20:39:40
【问题描述】:

任何人都可以在这方面提供帮助。我想从速度和时间计算一次旅行的总距离。当距离不低于最大距离但下降​​到低于最大行驶距离时,我可以获得结果,最大距离不会增加低于最大距离的行驶距离。当速度降低到最大水平以下距离值也在减少,实际上这需要添加到最大距离。

例如: 速度 = 60KM/HR, 时间 = 300SEC 然后距离 = 18KM 但是当速度降低到 40KM/HR 并且总时间为 450SEC 时,总距离需要添加到 18KM + ( 40 * 150 = 6KM) = 24KM 但是当速度降低到 40KM/HR 时,总行驶距离也降低到 18KM 以下。 这里 18KM 是 tripDistMax 的最大值,这个值需要添加到变速(最小/最大级别)。

希望您了解我的问题并寻求解决方案。

下面是代码。

double tripDistMax = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String tripDistance = tripDistanceCalculation();
    tvTripDistance.setText(tripDistance + " KM");
}

private String tripDistanceCalculation() {
    double distance = 0;
    distance = Double.parseDouble(tvTripDistance.getText().toString());
    String duration = time.getText().toString().trim();
    String split[] = duration.split(":");
    if (split.length == 3) {
        String mainSpeedString = tvSpeed.getText().toString().trim();
        int mainSpeed = Integer.parseInt(mainSpeedString);
        int hour = Integer.parseInt(split[0]);
        int minute = Integer.parseInt(split[1]);
        int seconds = Integer.parseInt(split[2]);
        totalSeconds = seconds + (minute * 60) + (hour * 60 * 60);
        if (tripDistMax <= distance) {
            tripDistMax = distance;
        }
        distance = (float) ((mainSpeed * totalSeconds) + tripDistMax) / 1000; //Dist=SpeedxTime
        return new DecimalFormat("#.#").format(distance) + "";
    }
    return "";
}

提前谢谢你。

【问题讨论】:

  • 首先,您问题中距离的计算不正确。 60公里/小时300秒不是18公里,而是5公里。将您的速度转换为 m/s(除以 3.6)或将您的秒数转换为小时,然后删除 /1000
  • 是的,您的示例应该在 300 秒内跑 5 公里,在 150 秒内跑 1.666...公里。这将加起来 6.666 公里。

标签: java android android-studio android-studio-3.0


【解决方案1】:

该代码 sn-p 中的问题是您在 onCreate 生命周期挂钩中调用了此函数一次。这意味着该组件无法记住之前的任何计算,因为它只是在再次调用该函数时才创建的。

您将需要一些对象来维持生命周期,或者更好的方法来存储以前的值。然后你可以让你的函数读取以前的数据,并添加到它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多