将浮点数转换为整数时的.NET错误? [英] .NET bug when converting float to integer?

查看:148
本文介绍了将浮点数转换为整数时的.NET错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 使用System; 
using System.Collections.Generic;
使用System.Linq;
使用System.Text;

命名空间CastVsConvert
{
类程序
{
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} \\\
,percentage.ToString());
Console.Write(Cast:{0} \\\
,newWidth.ToString());
Console.Write(Convert:{0} \\\
,newWidthConvert.ToString());
}
}
}

Cast和Convert是相同的,但它们不是...这里是输出:

  C: \\ Documents and Settings \Scott\My Documents\Visual Studio 2008\Projects\CastVsC 
onvert\CastVsConvert\bin\Debug> CastVsConvert.exe
百分比:0.8333333
演员:499
转换:500

有谁知道为什么.NET会返回不同的值价值在这里?

解决方案

它不是一个bug, cast 截断, convert rounds。



请参阅这个


Check it out: this little .NET Console Program yields interesting results...notice how I'm converting a float to an integer in two different ways:

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());
        }
    }
}

I would expect the output for "Cast" and "Convert" to be the same, but they're not...here's the output:

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

Does anybody know why .NET is returning different values here?

解决方案

Its not a bug, cast truncates, convert rounds.

See this

这篇关于将浮点数转换为整数时的.NET错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆