有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我在除以这两个整数时得到0.0?

我试图用一个固定的时间来显示一天过去的百分比。然而,当我把已经过去的时间除以一天的总时间(以秒为单位)时,我得到0.0。我将当前值放入控制台。感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    您正在执行整数除法,然后将其转换为double。你应该做:

    int numOfSecondsSinceMidnight = 61960;
    int totalDay = 86400;
    double percentDayPassed = 0;
    percentDayPassed = (((double)numOfSecondsSinceMidnight / totalDay)*100);
    System.out.println(percentDayPassed);
    

    或者更好的是,将numOfSecondsSinceMidnighttotalDay更改为doubles:

    double numOfSecondsSinceMidnight = 61960;
    double totalDay = 86400;
    double percentDayPassed = 0;
    percentDayPassed = ((numOfSecondsSinceMidnight / totalDay)*100);
    System.out.println(percentDayPassed);
    

    这两种印刷品:

    71.71296296296296