简体   繁体   中英

How to make negative of a variable? C++

I apologize if this error is the result of a typo, but I can't figure out how to make my variable negative when the correct syntax should be y=-x;

std::cout << "loop size = " << loop_size_ << std::endl;
core::Size neg_loop_size_ = -loop_size_;
std::cout << "neg loop size = " << neg_loop_size_ << std::endl;

When I run it, this is the result I get:

loop size = 4
neg loop size = 18446744073709551612

How do I get a new variable equal to -4?

This is undoubtedly a signedness issue. You have specified that neg_loop_size is core::Size . core::Size is likely meant to be a length-style measurement. A length cannot be negative. ("How many kilometers did you run today, Josy?", "Why, I ran negative 4 kilometers!")

So, the compiler and cout are correctly coercing -1 to "loop around" to the highest number possible with 8 bytes. Consider:

   18446744073709551612 + 4 - 1
 = 2^65 -1
 = 0xFFFFFFFFFFFFFFFF
 = (core::Size) 0 - 1

If you want a negative value, you will either need to do some string manipulation and conversion yourself, or choose a datatype that the compiler and cout will interpret as negative. For example:

int i = 0;
i -= 1;
std::cout << "i = " << i << std::endl;

I think the issue is Core:Size data type is unsigned. So you are having issue.

If you store the value in a integer you should get the required output.

  int main() {
      int i = 5;
      int j = -i;
      cout<<endl<< j << endl;

     return 1;
}

Output ---

$>:~/tmp$ vim c.cpp
$>:~/tmp$ g++ c.cpp
$>:~/tmp$ ./a.out
-5
$

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