Sco*_*rad 1 .net floating-point
看看它:这个小的.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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望"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
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么.NET在这里返回不同的值?
从Convert.ToInt32的返回值的文档:
值四舍五入到最近的32位有符号整数.如果值在两个整数之间,则返回偶数; 也就是说,4.5转换为4,5.5转换为6.
投射不会向上舍入 - 它只是截断.乘法的结果略低于500,因此强制转换将截断为499,而Convert.ToInt32将其舍入为500.