Click here to Skip to main content
14,176,353 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hello everyone, I am back yet with another question, I receive -0.0 20 times, well actually 19 , even though I need 20

double temp=20;

    for(int index = 1; index < temp; index++)
    {
    celsius(index);
    }
}
public static double celsius(double temperature)
{
    double celsius;

    celsius = (5/9) * ( temperature - 32);
    System.out.println(celsius);
    return celsius;
}
Posted
Comments
Sergey Alexandrovich Kryukov 29-Feb-12 19:33pm
   
Wow! You really need basic, very, very basic understanding of calculations and numeric types.
Also, before asking such questions, you always need to run your code under debugger.

Actually, you need to use the debugger if you have a slightest concern on your run-time behavior. If you just did not start using the debugger, you can consider that you did not start programming at all, not yet. Please do it immediately.

--SA

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

This is because 5/9 is incorrect. This is integer division, always returns 0 when a numerator is less than denominator.

If you simply change the order of multiplication, first integer operand will implicitly convert to double; and then all other operands will be converted to double, as the first operand temperature is declared double; and you will get a correct result:
celsius = (temperature - 32) * 5 / 9;


See: http://en.wikipedia.org/wiki/Celsius[^].

—SA
   
v3
Comments
   
Oh makes sense, but I did figure out it was the problem.
So i just hard coded it, but now I get some error.

public static void main(String[] args)
{
double temp=20;

for(int index = 0; index < temp; index++)
{
celsius(index);
}
}
public static double celsius(double temperature)
{
double celsius;

celsius = ((0.5555555555555556) * ( temperature - 32));
System.out.println("Fahrenheit\t\tCelsius");
System.out.println("=====================");
System.out.printf("%d\t\t%.1f\n",temperature,celsius);
return celsius;
}
Sergey Alexandrovich Kryukov 29-Feb-12 19:54pm
   
You don't need to do that. You pre-calculated immediate constant makes code less readable and does not improve performance. You should do what I suggested, or, better yet, explicitly define double constant:

double factor = 5d/9;

--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190525.1 | Last Updated 29 Feb 2012
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100