2014-12-07 112 views
-1

試圖找出一天中過去的時間百分比。我不知道我在做什麼錯,但編譯和執行代碼只是給我0.0,我不知道我做錯了什麼。已過去時間的百分比(Java)

class Time { 
public static void main(String[] args) { 
    // variable assignments apply to the time when I started 
    // writing program 
    int hour, minute, second; 
    hour = 11; 
    minute = 8; 
    second = 14; 

    int hoursToMinutes = hour * 60; 
    int minutesToSeconds = (hoursToMinutes + minute) * 60; 
    int secondsElapsed = minutesToSeconds; 
    System.out.println(secondsElapsed + " seconds have elapsed."); 

    int secondsPerDay = 24 * 60 * 60; 
    double percentageOfDayElapsed = secondsElapsed/secondsPerDay; 
    System.out.println(secondsPerDay); 
    System.out.println(percentageOfDayElapsed + "% of the day has elapsed."); 
    } 
} 
+2

INT除法代替浮點。 – 2014-12-07 16:21:22

+0

我沒有看過你的所有代碼,但我看到你用int分開,試試double percentOfDayElapsed =(double)secondsElapsed /(double)secondsPerDay; – TungstenX 2014-12-07 16:22:39

回答

2

secondsElapsed/secondsPerDay正在執行整數除法,這意味着沒有小數將永遠不會回來了。如果你想使用部門與小數,你可以投其中一個操作數爲double

double percentageOfDayElapsed = (double) secondsElapsed/secondsPerDay; 

而且,因爲這應該是一個百分比,我希望它由一百乘以:

double percentageOfDayElapsed = ((double) secondsElapsed/secondsPerDay) * 100; 

另一件事:second變量從未使用。也許它應該被添加到secondsElapsed

int secondsElapsed = minutesToSeconds + second; 
0
int secondsElapsed = minutesToSeconds; 
int secondsPerDay = 24 * 60 * 60; 

你跳水兩個整數!他們改爲雙打:

double secondsElapsed = minutesToSeconds; 
double secondsPerDay = 24 * 60 * 60; 

,然後做你的事業部:

double percentageOfDayElapsed = secondsElapsed/secondsPerDay; 
0

的問題是,你是一個整數除以整數。 它會給你一個小於1的數字。 由於它是一個整數,它將被截斷爲0.並且只有在它被轉換爲double之後。所以你想在分割之前將它轉換成雙精度。

變化分割線到:

double percentageOfDayElapsed = ((double)secondsElapsed/(double)secondsPerDay)*100;