-2

My C# code keeps returnng me a wrong conversion result. As far as i know, the conversion formula is correct, but it keeps displaying wrong results.

e.g: 70°F gives me 12,777777 °C. Can you check my code out ?

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

namespace Temperature
{
    class Program
    {    
        class Temperature
        {
            public double temp;

            public void Convert(double value)
            {
                double tEmp;
                tEmp = (value - 32) / 1.8;
                Console.WriteLine("The temperature in °C is :" + tEmp);
                Console.ReadKey();
            }
        }

        static void Main(string[] args)
        {
            double f;
            Temperature c = new Temperature();
            f = Console.Read();
            c.Convert(f);
        }
    }
}
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
wes
  • 23
  • 1

2 Answers2

13

your problem is

f = Console.Read();

It just reads the first character, not your entire line of input. Try

f = Convert.ToDouble(Console.ReadLine());

Here's a good answer on the difference between Console.Read vs. Console.ReadLine()

Community
  • 1
  • 1
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • 1
    Correct, this is the source of the problem, but you should explain *why* `Console.Read` of `70` gives `12.78` instead of `21.11` – p.s.w.g Nov 21 '14 at 14:56
  • Console.Read returns an Int32 which represents a single character that was read or -1. See http://msdn.microsoft.com/en-us/library/system.console.read – Sam Greenhalgh Nov 21 '14 at 14:58
  • Thanks. I didin't know about the "Convert.ToDouble" method. – wes Nov 21 '14 at 22:33
3

Console.Read() returns the ordinal value of the next character in the input stream.

The first character in your input stream is '7' which has an ordinal value of 0x0037. Represented as decimal this is 55 and (55-32)/1.8 is 12.7777.

You should be using Console.ReadLine() rather than Console.Read().

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490