我的 C# 控制台应用不是 运行 正确的计算

My C# console app is not running the correct calculations

我有一段代码可以将给定的输入转换为华氏度。

我尝试应用的公式是温度(无论用户输入什么)* 1.8 + 32。但是它返回错误的输出(68,如果我没记错的话应该是 64)。

我几乎尝试了所有方法:转换、在计算本身中提供类型,但没有任何帮助。

如果有人知道如何让它输出正确的值,请告诉我。

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");

这应该可以解决问题:

 int TempFahrenheit = (int)(Temperature * 1.8f + 32f);

Convert.ToInt32(1.8) 行将得到一个整数,这将使计算不正确。您需要先进行计算,然后如果需要将结果转换为整数。 为了更精确,将结果存储为浮点数可能更好:

float TempFahrenheit =  Temperature * 1.8f + 32f;

然后当你想显示它时,你可以只显示整数部分:

string displayTemp = TempFahrenheit.ToString("0")

一个整数是一个整数,所以如果你创建一个 1.8 的整数,那么它实际上就是 1 (显然是 2,使用 Convert.ToInt32(1.8)) .整数总是向下舍入。 如果要将 1.8 声明为不同的数据类型。您可以使用 1.8f 表示浮点数,1.8d 表示双精度数,或 1.8m 表示小数。

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");

source

注意:float 不如 double 精确,而 double 又不如 decimal 精确。在大多数情况下,double 或 float 都可以,也适用于您的用例。