I am learning to code with C# since I like what the language has to offer and in a learning exercise I was doing I came up with a problem.
The gist of the exercise was to learn declaring variables, using them and displaying them.
My code, which works, goes like this:
//Declare variables
float originalFahrenheit;
float calculatedFahrenheit;
float calculatedCelsius;
//Asks for fahrenheit
Console.Write("Enter temperature in fahrenheit: ");
originalFahrenheit = float.Parse(Console.ReadLine());
//Calculations
calculatedCelsius = ((originalFahrenheit - 32) / 9) * 5;
calculatedFahrenheit = ((calculatedCelsius * 9) / 5) + 32;
//Display calculations
Console.WriteLine(originalFahrenheit + " degrees fahrenheit is " + calculatedCelsius + " degrees celsius");
Console.WriteLine(calculatedCelsius + " degrees celsius is " + calculatedFahrenheit + " degrees fahrenheit");
Console.ReadKey();
When the user inputs "70" degrees fahrenheit the answers are displayed correctly.
Enter the temperature in fahrenheit: 70
70 degrees fahrenheit is 21.11111 degrees celsius
21.11111 degrees celsius is 70 degrees fahrenheit
Now, I tried using 'casting' just because and the code compiled but the results are different:
This is the code:
//Asks for fahrenheit
Console.Write("Enter temperature in fahrenheit: ");
originalFahrenheit = (float)Console.Read;
And this is the answer I got:
Enter the temperature in fahrenheit: 70
55 degrees fahrenheit is 12.77778 degrees celsius
12.77778 degrees celsius is 55 degrees fahrenheit
I would like to know why is this happening. Is casting just no good for situations like this or is my syntax bad?
One more question please. When changing:
originalFahrenheit = (float)Console.Read
to
originalFahrenheit = (float)Console.Readline()
I get an exception. See it in the picture below please:
Changing Console.Read to Console.ReadLine using casting
It basically tells me I cannot convert type 'string' to 'float'.
When changing:
originalFahrenheit = float.Parse(Console.ReadLine());
to
originalFahrenheit = float.Parse(Console.Read());
I get another exception. See it below please:
Changing 'Console.ReadLine' to 'Console.Read' using Parse
The exceptions tells me I cannot convert type 'int' to 'string'
Why does it happens? How does 'ReadLine' and 'Read' play out in the code?