Dingo F
Dingo F

Reputation: 25

Why is my c# program returning 0?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fahrenheit_to_Celsius_Converter
{
    class Program
    {
        static void Main(string[] args)
        {//Prompt user to enter a temperature
            Console.WriteLine("Please enter the temperature in fahrenheit you want to convert");
            //Sets variable fahr to the number entered
            string fahr = Console.ReadLine();
            //Just for testing debugging purposes displays what data is stored in fahr.
            Console.WriteLine(fahr);
            //Initializes an integer fahrint
            int fahrint;
            fahrint = int.Parse(fahr);
            //Just for testing debugging purposes displays what data is stored in fahrint.
            Console.WriteLine(fahrint);
            //Initializes an integer celcius
            decimal celcius;
            //Does the calculation that stores to a variable called celcius
            celcius = ((fahrint) - 32) * (5 / 9);
            //At this point the celcius variable print 0. It should print 5 if 41 is entered
            Console.WriteLine(celcius);
            string celciusstring;
            celciusstring = celcius.ToString();
            Console.WriteLine(celciusstring);



        }
    }
}

I have commented on what is happening in my code as much as possible. The program stores Fahrenheit as a string and converts it to a decimal fine. However, celcius = 0 instead of the correct number at the point where celcius = celcius = ((fahrint) - 32) * (5 / 9);. I am aware I spelt celcius wrong, but I do not believe it hase effected the code. Any solutions?

Thanks!

Upvotes: 2

Views: 191

Answers (2)

Jonesopolis
Jonesopolis

Reputation: 25370

Integer Division. 5 / 9 is always 0

(fahrint - 32) * (5 / 9)
                   ^^^  

You need to cast at least one of those values to a decimal:

celcius = (fahrint - 32) * (5M / 9);
//5 is of type Decimal now

Upvotes: 6

Dave Zych
Dave Zych

Reputation: 21887

All literal numbers are of type integer by default. When doing integer division, the result is "rounded" down to the nearest whole number, in this case 0. So the result is always 0.

You need to declare one of those as a decimal to force it to not perform integer division using m:

celcius = ((fahrint) - 32) * (5m / 9); //5 is now a decimal

Upvotes: 2

Related Questions