简体   繁体   中英

Is it difference between 0 and -0 in c++

I want to create a cycled linked list and I need to find max and min values in it, so I need some checkpoint to stop, and I want to do that with -0 in first element(it will be just a checkpoint not anything else). I don't want to use any else value because user can input new data into the list, if user inputs -0 I will simply replace it on 0 because from math side it is no difference between them (I don't use eternally-small digits :) ). I use integer values.

question is not profitable now. I try it and the result is they are same:

#include <iostream>

using namespace std;

int main() {
    if(0 != -0){
        cout << "they are different!";
    }else{
        cout << "they are same";
    }

    return 0;
}

Thanks to all.

As in maths 0 and -0 are the same value. You can not differentiate them in any way and so you can use this condition as you describe it.

Integer values in the nearly universal twos-complement system can't be negative zero - there's no representation for them. Negative zero simply doesn't exist.

Negative zero is possible with IEEE floating point numbers, but don't come about very often. Multiplying a negative number by 0.0 will do it.

I'd suggest finding another sentinel value.

This would require you store ints as doubles, mind. But you could do something like this.

signbit probably does the trick. If not, try taking the reciprocal. 1/+0.0 = +inf, 1/-0.0 = -inf. As a last ditch effort, do something like:

double d=-0.0;
bool is_neg = (*(uint64_t*)&d)&0x8000000000000000;

Use NaN as a checkpoint:

#include <iostream>
#include <limits>
struct cll {
  double value;
  cll * next;
};
int main() {
  int N = 5;
  double input[] = {1,2,3,4,5};
  cll * first = new cll;
  first->value = std::numeric_limits<double>::quiet_NaN();
  cll * next = first;
  for (int i = 0; i < N; ++i) {
    cll * last = new cll;
    next->next = last;
    last->value = input[i];
    last->next = first;
    next = last;
  }
  next = next->next;
  next = next->next;
  while (next->value == next->value)  {
    next = next->next;
  }
  next = next->next;
  while (next->value == next->value) {
    std::cout << next->value << '\n';
    next = next->next;
  }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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