java - 十进制负数和正数之和

标签 java c#

在 Java 和 C# 中:

int a = (int)(-1.5 + 2.5);
int b = (int)(-1.55 + 2.55);
int c = (int)(1.45 + 2.55);
// a = 1; b = 0; c = 4;

谁能解释为什么将正数加到小数点后 2 位或更多位的负数会导致小数点中断? “b = 0.99999999999999978”。

所以问题是 - 为什么是“-1.5 + 2.5 = 1”,但“-1.55 + 2.55 = 0”?

最佳答案

这是因为 double 类型是一个近似值。

通常 double 表示 IEEE 754标准型decimal64


Math.Round allows you to specify a MidpointRounding:

ToEven - When a number is halfway between two others, it is rounded toward the nearest even number.

AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.

示例:

var val = (int)Math.Round((-1.55 + 2.55), 1, MidpointRounding.ToEven);
Console.WriteLine(val);

输出:1


初学者的常见错误是编写如下代码:

for (double i = 0.0; i == 6.0; i+=0.1)
{
    Console.WriteLine(i);
}

提示:这不会在大约 60 步后结束。

关于java - 十进制负数和正数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626944/

相关文章:

java - 被java语法搞糊涂了

c# - 如何从数组创建将生成重复键的字典

c# - MSMQ自定义消息格式

java - 需要显示响应,它是 View 页面上的 html 代码

java - Play Framework 2.4 : Use Spring Depedency Injection with Play-Framework Instead of Guice

java - Android:如何在我自己的类中使用为 Activity 定义的方法?

c# - JSON Newtonsoft C# - 反序列化 JSON 文件中的特定字段

c# - 如何改变 XNA 中的色调?

c# - ViewStateMode 与 EnableViewState

java - Jetty 9 HTTP客户端: How to get the request content?