我想知道C++中复合赋值的执行流程。我遇到了一个 CodeChef question ,我在这里计算 NCR mod p 值并将它们加在一起得到最终答案:
// correct
for(int i=min1; i<=max1; i+=2){
ans = (ans+ncr_mod_p(n,i))%mod;
}
// incorrect
for(int i=min1; i<=max1; i+=2){
ans+=ncr_mod_p(n,i)%mod;
}
这是由于整数溢出而发生的。那么,复合赋值的执行顺序是怎样的呢?
假设我们有一个方程
a+=b%c
那么执行顺序是什么:a = (a+b)%c
// OR
a = a+(b)%c;
最佳答案
这个说法
ans+=ncr_mod_p(n,i)%mod;
相当于声明ans = ans + ( ncr_mod_p(n,i)%mod );
如您所见,它与声明不同ans = (ans+ncr_mod_p(n,i))%mod;
来自 C++ 14 标准(5.18 赋值和复合赋值运算符)7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.
关于c++ - C++中的复合赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65811703/