確認してください: この小さな .NET コンソール プログラムは興味深い結果をもたらします... 2 つの異なる方法で浮動小数点数を整数に変換する方法に注目してください。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastVsConvert
{
class Program
{
static void Main(string[] args)
{
int newWidth = 0;
CalculateResizeSizes(600, 500, out newWidth);
}
static void CalculateResizeSizes(int originalWidth, int maxWidth, out int newWidth)
{
float percentage = 1.0F;
percentage = maxWidth / (float)originalWidth;
newWidth = (int)((float)originalWidth * percentage);
int newWidthConvert = Convert.ToInt32((float)originalWidth * percentage);
Console.Write("Percentage: {0}\n", percentage.ToString());
Console.Write("Cast: {0}\n", newWidth.ToString());
Console.Write("Convert: {0}\n", newWidthConvert.ToString());
}
}
}
「Cast」と「Convert」の出力は同じになると思いますが、そうではありません...出力は次のとおりです。
C:\Documents and Settings\Scott\My Documents\Visual Studio 2008\Projects\CastVsC
onvert\CastVsConvert\bin\Debug>CastVsConvert.exe
Percentage: 0.8333333
Cast: 499
Convert: 500
ここで.NETが異なる値を返す理由を知っている人はいますか?