-2

I'm trying to get Celsius to take the Fahrenheit temperature as an argument, then return the temperature in Celsius

class Exercise1
{
    static void Main(string[] args)
    {
        double fahrenheit; 
        Console.WriteLine("Enter farenheit: ");
        fahrenheit = double.Parse(Console.ReadLine());

        double cels;

        Exercise1 me = new Exercise1();
        cels = me.Celsius(fahrenheit);

        Console.WriteLine(cels);
    }

    public double Celsius(double fahrenheit)
    {
        double celsius;
        celsius = 5 / 9 * (fahrenheit - 32);
        return celsius;
    }
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Josh
  • 49
  • 1
  • 1
  • 2
  • There are many similar question already. I.e. duplicate (also it talks about `decimal` issue/solution is the same). Or if you want just `double` - read this one - http://stackoverflow.com/questions/488942/what-is-the-best-practice-to-make-division-return-double-in-c-sharp – Alexei Levenkov Nov 24 '14 at 00:43

2 Answers2

2

Your problem is integer division in your Celsius function. This line

    celsius = 5 / 9 * (fahrenheit - 32);

Will always be 0 because 5 / 9 will be divided as integers which will always give you 0. To force floating-point division, one if your integers must be a double. So do this:

    celsius = 5.0 / 9 * (fahrenheit - 32);

Note the 5.0 will force floating-point division.

Reticulated Spline
  • 1,892
  • 1
  • 18
  • 20
0

5 / 9 would be seen as integers and thus make the entire calculation integer maths in this case.

Meaning you are essentially getting 0 * (fahrenheit - 32).

Cast either or both 5 and 9 to a double to force floating point maths.

bizzehdee
  • 20,289
  • 11
  • 46
  • 76