简体   繁体   English

为什么C#为浮点类型实现前/后递增/递减运算符?

[英]Why does C# implement pre/post-increment/decrement operators for floating point types?

What's so special about adding/subtracting 1 to/from a floating point value that it deserves a dedicated operator? 在浮点值中添加/减去1值得专用的运算符有什么特别之处?

double a = -0.001234129;
a++; // ? 

I've never felt the need to use such a construction; 我从来没有觉得需要使用这样的结构; it looks really weird to me. 它看起来很奇怪。 But if I ever had to, I'd feel much more comfortable with just: 但如果我不得不这样做,我会感到更舒服:

a += 1;

Maybe it's because of my strong C++ background, but to me it makes a variable look like an array indexer. 也许是因为我强大的C ++背景,但对我而言,它使变量看起来像数组索引器。

Is there any reason for this? 这有什么理由吗?

The ++ and -- operators operate on all other number types, why make an exception for floating point numbers? ++--运算符对所有其他数字类型进行操作,为什么浮点数会出现异常? To me, that would be the more surprising choice. 对我来说,这将是更令人惊讶的选择。


Note that C++ also implements these for floating point: 请注意,C ++也为浮点实现了这些:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    double a = 0.5;
    cout << a << '\n';
    ++a;
    cout << a << '\n';
    return 0;
}

Output: 输出:

0.5
1.5

My guess is that the reason is consistency with C/C++. 我的猜测是,原因是与C / C ++的一致性。

I agree with you, that it's kind of weird - the '++' operator has some special meaning for integer values: 我同意你的观点,它有点奇怪 - '++'运算符对整数值有一些特殊含义:

  1. It translates to INC assembly instruction, 它转换为INC汇编指令,
  2. It represents changing the value by a special amount (ie by the smallest possible amount), and because of this it's used in iterations. 它表示将值更改特殊量(即以最小可能量),因此它在迭代中使用。

For floating point numbers, however, the value 1.0 is not any special value (from machine point of view). 但是,对于浮点数,值1.0不是任何特殊值(从机器的角度来看)。 You also shouldn't use it for iterations (in other words: if you're using it you should usually consider using an int) as well as it doesn't have a designated INC assembly instruction. 您也不应该将它用于迭代(换句话说:如果您正在使用它,您通常应该考虑使用int),并且它没有指定的INC汇编指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM