java - Why do I need to add an 'f' to value so my code outputs the right value? -


this question has answer here:

the following code works ::

public class avgspeed{     public static void main(string[] args){         double kph, km, hours, seconds, minutes, time;         km = (1.6 * 24);         hours = 1;         minutes = 2/3f;         seconds = 35/3600f;         time = hours + minutes + seconds;         kph = km/time;         system.out.println(kph);     } } 

if remove f's minutes , seconds, keeps printing out 38.4, not right. should number close 22.906

i don't know reason why need add f, did on whim. thought declaring 2 variables double enough?

declaring variables doubles doesn't make 2 or 3 double. conversion double happens after 2/3 computed in integer arithmetic. fix this, calculation in double arithmetic:

        minutes = 2.0/3;         //         ^ double         seconds = 35.0/3600;         //         ^ double 

the trailing f appended made 3f , 3600f float literals. that's close want, not doubles.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -