Click here to Skip to main content
15,914,066 members
Please Sign up or sign in to vote.
2.00/5 (1 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

C#
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

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:
C#
celsius = (temperature - 32) * 5 / 9;


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

—SA
 
Share this answer
 
v3
Comments
Alexander Alekseyevich Fedoseev 29-Feb-12 19:34pm    
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900