为什么Java的%操作符给出比我的负面股息计算器不同的结果? [英] Why does Java's % operator give different results than my calculator for a negative dividend?

查看:91
本文介绍了为什么Java的%操作符给出比我的负面股息计算器不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么用计算器-1mod26 = 25,但在C或Java -1%26 == -1 。我需要一个程序,它解决它像计算器。有没有两者之间的区别吗?

How come on a calculator -1 mod 26 = 25, but in C or Java -1 % 26 == -1. I need a program which solves it like the calculator. Is there a difference between the two?

推荐答案

这两个答案(25 -1)是有效的。这只是不同的系统有不同的约定。

Both answers (25 and -1) are valid. It's just that different systems have different conventions.

一个我看到的最常见的(数学)是:

The one I see the most common (in mathematics) is:

quotient  = floor(x / y)
remainder = x - quotient * y

其中,地板()是圆接近负无穷大。

这是你的计算器是给你的惯例。 (数学也采用了这种约定)。

This is the convention that your calculator is giving you. (Mathematica also uses this convention.)

一个我想大多数的编程语言采用的是:

The one I think most programming languages use is:

quotient  = integerpart(x / y)
remainder = x - quotient * y

其中, integerpart()是一样的(浮点 - > integer)强制转换。 (向零舍入)

Where integerpart() is the same as a (float -> integer) cast. (round towards zero)

一些公约喜欢保持其余符号相同的操作数之一

Some conventions like to keep the remainder the same sign as one of the operands.

同样的道理也适用于分压器的迹象。不同的约定是不同的。

The same thing applies to the sign of the divider. Different conventions are different.

这篇关于为什么Java的%操作符给出比我的负面股息计算器不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆