English 中文(简体)
将双倍转换为 C # 中的一整字
原标题:Converting a double to an int in C#
  • 时间:2012-05-25 12:15:19
  •  标签:
  • c#
  • int
  • double

在我们的代码中,我们有一个双倍的, 我们需要转换成一整点。

double score = 8.6;
int i1 = Convert.ToInt32(score);
int i2 = (int)score;

有人能解释为什么 i1! > = i2 ?

我得到的结果是: i1=9i2=8

最佳回答

因为""http://msdn.microsoft.com/en-us/library/ffdk7eyz.aspx" {acode>Conver.ToInt32 回合:

Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

......而石膏""http://msdn.microsoft.com/en-us/library/yht2cx7b.aspx"" 直线 :

When you convert from a double or float value to an integral type, the value is truncated.

<强度 > 更新: 见下文Jeppe Stig Nielsenss 评论关于其他差异的评论(但如果 score 是一个实际数字,这里的情况就是如此,则无法发挥作用)。

问题回答

在小数点后,投球会忽略任何事物, 所以8.6变成8。

convert.toInt32(8.6) 是确保双倍四舍五入到最接近的整数的安全方式, 在这种情况下, 9。

你们可以双倍地绕着你们,然后抛下一部分。

(int)Math.Round(myDouble);

在所提供的示例中,您的小数点为<强>8.6 。如果是8.5或9.5,那么“强>i1 = i2

<强 > 排除:

不论小数部分为何,第二个语句 int i2 = (int)score 将丢弃小数部分,而只需返回整数部分。当数据丢失时,要做的事情非常危险。

现在,对于第一个语句,可以发生两件事。 如果小数部分为 5, 也就是说, 这是经过一半, 就要做出一个决定 。 我们往上还是往下? 在 C # 中, 转换类执行银行家的四舍五入 。 见 < a href=" https:// stackoverflow.com/ quesress/3111696/ why- does- net- use- bankers- rounding- as- default > > > this < / a > 回答更深层次的解释。 简单地说, 如果数字是偶数的话, 如果数字是奇数的话, 则按四舍四舍五入 。

例如,考虑:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

投到本部就把非内插部件扔掉





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签