当我可以在C#中使用浮点数或双精度数时,为什么要使用整数? [英] Why should I use Integers when I could just use floats or doubles in C#?

查看:219
本文介绍了当我可以在C#中使用浮点数或双精度数时,为什么要使用整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在学习C#。

我不明白为什么有人会在使用浮点数或双打时使用整数...

I don't get why anyone would use Integers when they could use floats or doubles..

浮点数将加/减整数和十进制数,那么为什么有人会费心使用普通的旧整数?

Floats will add/subtract whole numbers AND decimal numbers so why would anyone ever bother using a plain old integer?

好像浮点数或double会处理Integer可以处理的任何事情。数字也是..

Seems like floats or double will take care of anything that an Integer can do with the bonus of being able to handle . numbers too..

谢谢!

推荐答案

主要原因是我们通常更喜欢使用整数分数而不是固定精度小数。对于有理分数,(1/3)乘以3总是1.(1/3)加(2/3)总是1.(1/3)乘以2是(2/3)。

The main reason is the same reason we often prefer to use integer fractions instead of fixed-precision decimals. With rational fractions, (1/3) times 3 is always 1. (1/3) plus (2/3) is always 1. (1/3) times 2 is (2/3).

为什么?因为整数分数是精确的,就像整数一样精确。

Why? Because integer fractions are exact, just like integers are exact.

但是对于固定精度的实数 - 它并不那么漂亮。如果(1/3)是 .33333 ,那么3次(1/3)将不是1.如果(2/3)是 .66666 ,然后(1/3)+(2/3)不会是一个。但如果(2/3) .66667 ,那么(1/3)次2将不会是(2/3)而1减1(1/3)将不会是(2/3)。

But with fixed-precision real numbers -- it's not so pretty. If (1/3) is .33333, then 3 times (1/3) will not be 1. And if (2/3) is .66666, then (1/3)+(2/3) will not be one. But if (2/3) is .66667, then (1/3) times 2 will not be (2/3) and 1 minus (1/3) will not be (2/3).

当然,你无法通过使用更多的地方来解决这个问题。没有十进制数字将允许您准确地表示(1/3)。

And, of course, you can't fix this by using more places. No number of decimal digits will allow you to represent (1/3) exactly.

浮点是固定精度的实数格式,就像我上面的固定精度小数一样。它并不总是遵循您可能期望的天真规则。请参阅经典论文每个计算机科学家应该知道的关于浮点运算的内容

Floating point is a fixed-precision real format, much like my fixed-precision decimals above. It doesn't always follow the naive rules you might expect. See the classic paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.

要回答您的问题,首先应该尽可能使用整数,并且只在必要时使用浮点数。而且你应该永远记住,浮点数的精度有限,并且比较两个浮点数以确定它们是否相等可以给出你可能没想到的结果。

To answer your question, to a first approximation, you should use integers whenever you possibly can and use floating point numbers only when you have to. And you should always remember that floating point numbers have limited precision and comparing two floating point numbers to see if they are equal can give results you might not expect.

这篇关于当我可以在C#中使用浮点数或双精度数时,为什么要使用整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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