如何添加两个java.lang.Numbers? [英] How to add two java.lang.Numbers?

查看:17
本文介绍了如何添加两个java.lang.Numbers?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数字.例如:

Number a = 2;
Number b = 3;
//Following is an error:
Number c = a + b;

为什么数字不支持算术运算?无论如何,我将如何在 Java 中添加这两个数字?(当然,我是从某个地方获取它们的,我不知道它们是整数还是浮点数等).

Why arithmetic operations are not supported on Numbers? Anyway how would I add these two numbers in java? (Of course I'm getting them from somewhere and I don't know if they are Integer or float etc).

推荐答案

你说你不知道你的数字是整数还是浮点数...当你使用 Number 类时,编译器也不知道您的数字是整数、浮点数还是其他一些东西.结果,像 + 和 - 这样的基本数学运算符不起作用;计算机不知道如何处理这些值.

You say you don't know if your numbers are integer or float... when you use the Number class, the compiler also doesn't know if your numbers are integers, floats or some other thing. As a result, the basic math operators like + and - don't work; the computer wouldn't know how to handle the values.

开始编辑

基于讨论,我认为一个例子可能会有所帮助.计算机将浮点数存储为两部分,系数和指数.因此,在理论系统中,001110 可能被分解为 0011 10,或 32 = 9.但正整数将数字存储为二进制,因此 001110 也可能意味着 2 + 4 + 8 = 14.当您使用 Number 类时,您是在告诉计算机您不知道数字是浮点数还是整数或什么,所以它知道它有 001110 但它不知道这意味着 9 或 14 或其他一些值.

Based on the discussion, I thought an example might help. Computers store floating point numbers as two parts, a coefficient and an exponent. So, in a theoretical system, 001110 might be broken up as 0011 10, or 32 = 9. But positive integers store numbers as binary, so 001110 could also mean 2 + 4 + 8 = 14. When you use the class Number, you're telling the computer you don't know if the number is a float or an int or what, so it knows it has 001110 but it doesn't know if that means 9 or 14 or some other value.

结束编辑

您可以做一些假设并转换为其中一种类型来进行数学计算.所以你可以有

What you can do is make a little assumption and convert to one of the types to do the math. So you could have

Number c = a.intValue() + b.intValue();

你也可以变成

Integer c = a.intValue() + b.intValue();

如果您愿意接受一些舍入误差,或者

if you're willing to suffer some rounding error, or

Float c = a.floatValue() + b.floatValue();

如果您怀疑自己处理的不是整数,并且可以解决可能的小精度问题.或者,如果您更愿意接受小的性能打击而不是那个错误,

if you suspect that you're not dealing with integers and are okay with possible minor precision issues. Or, if you'd rather take a small performance blow instead of that error,

BigDecimal c = new BigDecimal(a.floatValue()).add(new BigDecimal(b.floatValue()));

这篇关于如何添加两个java.lang.Numbers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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