我最近开始学习 C#,我写了一个简单的练习,需要将输入从华氏温度转换为摄氏温度,然后再转换回来。代码很简单,这是我的努力(我假设用户输入数字):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class DegreeConversion
{
static void Main(string[] args)
{
Console.Write("Insert far -> ");
float far = float.Parse(Console.ReadLine());
float cel = (far - 32) / 9 * 5;
Console.WriteLine(far " degrees Fahrenheit is " cel " degrees Celsius");
float far2 = cel * 9 / 5 + 32;
Console.WriteLine(cel " degrees Celsius is " far2 " degrees Fahrenheit");
}
}
}
这是运行的,但是如果我在返回华氏温度时尝试输入0 ,我会得到类似 -1.525879E-06 的东西。我考虑过近似错误,也许是取消。我修改了一些以前的代码,特别是我改变了这个
float far2 = cel * 9 / 5 + 32;
对此
float far2 = cel * 9 / 5;
float newFar = far2 + 32;
现在输出为0!
我想这种行为与 c# 编译器有关,它重新排列了代码以获得更好的性能。我认为第一个代码应该在 CPU 寄存器中实现所有操作,而第二个代码将它们保存在内存中。我对么?你能解释一下在这种情况下发生了什么以及近似是如何工作的吗?
提前致谢!