gpt4 book ai didi

带负操作数的 C++ size_t 模运算

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:51 27 4
gpt4 key购买 nike

因此,模运算可以为您提供三个值:

然后:

-7 % 5 = 3(数学,余数 >= 0)

-7 % 5 = -2 (C++)

-7 % (size_t)5 = 4 (C++)

另一个例子:

-7 % 4 = 1(数学,余数 >= 0)

-7 % 4 = -3 (C++)

-7 % (size_t)4 = 1 (C++)

当左手操作数为正时,三种方法的答案都是一样的。但是对于负值,他们似乎都有自己的方法。 C++中无符号操作数取模运算的值是如何计算的?

最佳答案

这就是混合有符号和无符号值时发生的情况——困惑!

[C++14: 5.6/2]: The operands of * and / shall have arithmetic or unscoped enumeration type; the operands of % shall have integral or unscoped enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result.

现在,请看下面的粗体段落(假设您的 size_t 与您的 int 具有相同的排名;这总是正确的):

[C++14: 5/10]: Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

  • If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions (4.5) shall be performed on both operands.61 Then the following rules shall be applied to the promoted operands:
    • If both operands have the same type, no further conversion is needed.
    • Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.
    • Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.
    • Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.
    • Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

简而言之,您的 -7正在变成 std::numeric_limit<size_t>::max() + 1 - 7 (无论您的平台上有什么),并且正在对该值执行计算。事实上,on my platform, that confirms the result of 1 .

关于带负操作数的 C++ size_t 模运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39337196/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com