檢查出來:這個小.NET控制檯程序得出了有趣的結果...注意一下,我在兩種不同的方式浮點數轉換成整數:將浮點數轉換爲整數時的.NET錯誤?
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());
}
}
}
我希望爲「演員」的輸出和「轉換」是相同的,但它們不是...這裏是輸出:
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這裏返回的值不同?