简体   繁体   English

我应该使用 x = -x, 将负数转换为正数,反之亦然(在 C++ 中)?

[英]Should I use x = -x, to convert a negative number to a positive number and vice versa (in C++)?

I was wondering if I should use this "x = -x" to convert a negative number to a positive number or a positive number to a negative number in C++.我想知道我是否应该使用这个“x = -x”在 C++ 中将负数转换为正数或将正数转换为负数。 I mean is working pretty well so far, but I'm not sure if is recommended or not.我的意思是到目前为止工作得很好,但我不确定是否推荐。

I would appreciate some feedback about this thing.我会很感激一些关于这件事的反馈。 Thanks!!谢谢!!

int x = 10;
if (x > 0) {
    x = -x;
}
cout << x; // x = -10;

It is fine to do it that way.这样做很好。 You shouldn't have to worry about something like that.你不应该担心这样的事情。 If you're worried about performance, you should either mesure performance or check what assembly it generates.如果您担心性能,您应该测量性能或检查它生成的程序集。

I've created a compiler explorer example .我创建了一个编译器资源管理器示例 It compares the assembly for both x = - x;它比较x = - x;的程序集x = - x; and x *= -1;并且x *= -1; . . You can clearly see, even if you don't know assembly, that it generates the same code.即使您不了解汇编,您也可以清楚地看到它生成相同的代码。 And not very much of it anyway!反正也不是很多! (And it goes away when optimiser flags are on. (当优化器标志打开时它就会消失。

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

相关问题 如何在C++中将数字转换为字符串,反之亦然 - How to convert a number to string and vice versa in C++ 如何在C ++中从字符串转换为数字,反之亦然? - How to convert from string to a number, and vice-versa in C++? 如何在 C++ 中将月份名称(3 个字母缩写)转换为月份编号,反之亦然? [等候接听] - How can I convert month names (3 letter abbreviation) to month number, and vice versa, in C++? [on hold] 在c ++中,将正数转换为1并将负数转换为0的最快方法 - in c++, the fastest way to convert a positive number to 1 and negative to 0 如果 x 为正,我如何将 x 设置为负值,如果 x 为正,我如何将其设置为负。 c++ - How do i set x to be a negative value if x is positive, and if x is positive how do i set it to be negative. c++ C ++ | 将int转换为byte [4],反之亦然 - C++ | Convert int to byte[4] and vice versa C++ 将字符串转换为十六进制,反之亦然 - C++ convert string to hexadecimal and vice versa 位屏蔽以确定数字是正数还是负数c ++ - Bit masking to determine if number is positive or negative c++ C++ 计算数组中正/负数的数量 - C++ counting number of positive/negative numbers from an array C++ - 负数和正数之间的比较返回 false - C++ - Comparison between negative and positive number returns false
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM