Converting a double to an int in C#(在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中将 double 转换为 int
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
