私は最近 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 レジスタに実装し、2 番目のコードはそれらをメモリに保存する必要があると思います。私は正しいですか?この場合、何が起こっているのか、近似がどのように機能するのか説明できますか?
前もって感謝します!