Reputation: 121
I have a piece of code that converts given input to degrees Fahrenheit.
The formula I am trying to apply is Temperature (so whatever the user inputs) * 1.8 + 32. However it gives back a wrong output (68 where it should be 64 if I recall correctly).
I tried just about everything: converting, supplying a type in the calculation itself, but nothing helped.
If anyone knows how I can make it output the proper value please inform me.
int Temperature = 18;
Console.Write("Input the temperature in degrees Celcius. \n");
Temperature = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The temperature is " + Temperature + "°C");
int TempFahrenheit = Temperature * Convert.ToInt32(1.8) + 32;
Console.WriteLine("Converted to degrees Fahrenheit this is " + TempFahrenheit + "°F");
Upvotes: 0
Views: 131
Reputation: 752
An integer is a whole number, so if you make an int which is 1.8, that will make it 1 actually (apparently 2, with Convert.ToInt32(1.8)). Integers always get rounded down. If you want to declare 1.8 as a different datatype. you could use 1.8f for a float, 1.8d for a double, or 1.8m for a decimal.
int Temperature = 18;
Console.Write("Input the temperature in degrees Celcius. \n");
Temperature = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The temperature is " + Temperature + "°C");
//changed 1.8 to double
int TempFahrenheit = Temperature * 1.8d + 32;
Console.WriteLine("Converted to degrees Fahrenheit this is " + TempFahrenheit + "°F");
Note: float is less precise than a double, which is less precise than a decimal. In most cases, a double or float will be fine, also for your use case.
Upvotes: 0
Reputation: 1451
This should do the trick:
int TempFahrenheit = (int)(Temperature * 1.8f + 32f);
The line Convert.ToInt32(1.8) will result in a whole number, which will make the calculation incorrect. You need to do the calculation first, then if you need to convert the result to an integer. It may be better to store the result as a float for more precision:
float TempFahrenheit = Temperature * 1.8f + 32f;
Then when you want to display it you can do this just to display the integer part:
string displayTemp = TempFahrenheit.ToString("0")
Upvotes: 2