Why does Decimal.Divide(int, int) work, but not (int / int)?(为什么 Decimal.Divide(int, int) 有效,但 (int/int) 无效?)
问题描述
为什么将两个 32 位 int 数除为 (int/int) 返回给我 0,但如果我使用 Decimal.Divide() 我得到正确答案?我绝不是 C# 人.
How come dividing two 32 bit int numbers as ( int / int ) returns to me 0, but if I use Decimal.Divide() I get the correct answer? I'm by no means a c# guy.
推荐答案
int是整数类型;将两个整数相除执行 integer 除法,即小数部分被截断,因为它不能存储在结果类型中(也是 int!).相比之下,Decimal 有一个小数部分.通过调用 Decimal.Divide,您的 int 参数会隐式转换为 Decimals.
int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
您可以通过将至少一个参数显式转换为浮点类型来强制对 int 参数进行非整数除法,例如:
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.:
int a = 42;
int b = 23;
double result = (double)a / b;
这篇关于为什么 Decimal.Divide(int, int) 有效,但 (int/int) 无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Decimal.Divide(int, int) 有效,但 (int/int) 无效?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
