C++操作员(不确定)

发布于 2024-12-11 09:52:29 字数 178 浏览 0 评论 0原文

是否有一个 C++ 运算符可以用于 for 循环,根据其中一个变量是否小于或大于 0 来添加或减去变量。 例如

int a;
int b;
for(int i=0;i<some_number; i++)
  result = a +< b
  result = a-> b

Is there a c++ operator that i could use for a for loop where it would add or subtract to variables based on whether one of the variables is less than or greater 0.
For instance

int a;
int b;
for(int i=0;i<some_number; i++)
  result = a +< b
  result = a-> b

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

缘字诀 2024-12-18 09:52:29

不可以。

您可以与 ?: 运算符结合使用。

int a;
int b;
for(int i=0;i<some_number; i++)
  result = (a < b)? result+b:result-b;

也就是说,如果我正确理解你的例子。

-> 是现有的解引用运算符。

运算符?: 相当于if...else 结构。如果?之前的语句计算结果为true,则执行?之后的语句,否则执行: 被执行。

No.

You can combine with the ?: operator.

int a;
int b;
for(int i=0;i<some_number; i++)
  result = (a < b)? result+b:result-b;

That is if I understood your example correctly.

-> is an existing dereference operator.

Operator ?: is an equivalent to the if...else construct. If the statement before ? evaluates to true, the statement right after the ? gets executed, otherwise the statement after the : gets executed.

叫嚣ゝ 2024-12-18 09:52:29

你想要这样的东西吗?

result += a > 0 ? b : -b;

请注意,如果 a == 0,这将减去 b,这并不完全是您所要求的。

Do you want something like this?

result += a > 0 ? b : -b;

Note that this will subtract b if a == 0, which isn't quite what you asked for.

∞琼窗梦回ˉ 2024-12-18 09:52:29

不是直接的,但是 三元运算符 很接近。

for(int i=0;i<some_number; i++)
    result = (a > 0)?(a):(b);

当 a 大于 0 时,此行等效于 result = a,否则等效于 result = b

也可以写成 result = a?a:b;,但较长的形式更具可读性。

Not directly, but the ternary operator is close.

for(int i=0;i<some_number; i++)
    result = (a > 0)?(a):(b);

This line will be equivalent to result = a when a is greater than 0, and result = b elsewise.

It could also be written as result = a?a:b;, but the longer form is more readable.

撩心不撩汉 2024-12-18 09:52:29

不确定这是否有帮助?

result = a + (b*(a < b));
result = a - (b*(a > b));

基本上,(a < b) 被转换为布尔值,基本上是 1(真)或 0(假)。 b 乘以 0 当然是零,所以没有添加任何内容,而 b 乘以 1 正是 b 的值。

Not sure if this would be any help?

result = a + (b*(a < b));
result = a - (b*(a > b));

Basically, (a < b) is converted into a boolean, which is basically either 1 (true) or 0 (false). b multiplied by 0 is of course zero, so nothing is added, and b multiplied by 1 is exactly b's value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文