在 C# 中将 double 转换为 int

6

本文介绍了在 C# 中将 double 转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在我们的代码中,我们需要将 double 转换为 int.

In our code we have a double that we need to convert to an int.

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

谁能解释一下为什么i1 != i2?

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

The result that I get is that: i1 = 9 and i2 = 8.

推荐答案

因为 Convert.ToInt32 回合:

Because Convert.ToInt32 rounds:

返回值:四舍五入到最接近的 32 位有符号整数.如果值在两个整数之间,返回偶数;即4.5转4,5.5转6.

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.

...而演员截断:

当您从 double 或 float 值转换为整数类型时,值被截断.

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

更新:有关其他差异,请参阅下面 Jeppe Stig Nielsen 的评论(但是,如果 score 是实数,就像这里的情况一样,这些差异就不会起作用).

Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score is a real number as is the case here).

这篇关于在 C# 中将 double 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14