1

I've got a problem. I'm attempting to make a Farenheit to Celcius calculator, and when I do the fraction part of math, it kinda doesn't work. It's either 0 or 1.

private void toCelcius_Click(object sender, EventArgs e)
{
    double F = double.Parse(temperatureBox.Text);
    double fm32 = F - 32;
    double fraction = (9 / 5);
    double newTemp = fraction*fm32;

    temperatureLabel.Text = newTemp.ToString();
}

I've been using 100 as my test number, and everytime I send 100 to the textbox, it returns 68. It should be somewhere around 30ish.

Currently the program only senses the fraction as a 1. I tried using decimal instead of using double, but that breaks the newTemp problem. I tried using float, but got same results as a double. I have no freaking idea whats going on but it's very frustrating.

If anyone knows how to fix this, I'd be very thankful.

EDIT: Facepalm it's been such a long time since I've used doubles, forgot I needed to have the .0 after each number.

John Olivas
  • 309
  • 1
  • 2
  • 14

2 Answers2

5

You should put double for your number:

private void toCelcius_Click(object sender, EventArgs e)
{
    double F = double.Parse(temperatureBox.Text);
    double fm32 = F - 32;
    double fraction = ((double)9 / 5);
    double newTemp = fraction*fm32;

    temperatureLabel.Text = newTemp.ToString();
}

Otherwise, 9 will be read as int since this is the base C# literal for number (without comma or any other suffix like D). That is why you always get fraction as 1 because: 9/5 = 1.8 will be read as 1 in int

Alternatively, you could do this:

double fraction = (9D / 5); //the shortest (credit for Coxy)

Or, for more readability:

double fraction = (9.0 / 5); //like what we have in math (as pointed out by Michael Burr)
Ian
  • 30,182
  • 19
  • 69
  • 107
2

Alternatively use;

Double fraction = 9.0 / 5.0;
John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • yea, I forgot I had to use the .0's after each number for a double.. lol - thanks – John Olivas Jan 28 '16 at 02:57
  • @JohnOlivas actually for you case, you only need to put `.0` for any **one** of the numbers, the other will be automatically promoted for operation. But writing in both for readability is fine too. ;) – Ian Jan 28 '16 at 03:08