简体   繁体   English

模运算符(%)给出不同的结果

[英]Modulo Operator (%) gives divergent results

Given this Example: 鉴于此示例:

std::vector<int> numbers = {5,6,7}; //size is 3
int i = -1; 
std::cout << i % 3 <<"\n";                  // output: -1
std::cout << i % numbers.size() << "\n";    // output: 0

basically in both statements im processing -1 % 3 but the compiler outputs different numbers. 基本上在两个语句中我处理-1%3但编译器输出不同的数字。 I don't understand this outcome, maybe someone can explain it to me. 我不明白这个结果,也许有人可以向我解释。

edit: as @Chris,@Keith Thompson @AnT suggested the snippet 编辑: @ Chris,@ Keith Thompson @AnT建议片段

std::cout << std::numeric_limits<std::size_t>::max() % 3 <<"\n";     //output: 0
std::cout << i % numbers.size() << "\n";                            // output: 0

prints the expected output. 打印预期的输出。 Thanks for the helpful advice to everyone! 感谢大家的有益建议!

i % 3 is what you expect and, since C++11, has defined semantics rather than having an implementation-defined (if I recall correctly) result. i % 3是你所期望的,因为C ++ 11定义了语义而不是实现定义(如果我没记错)结果。

numbers.size() has an unsigned type ( std::size_t ). numbers.size()具有无符号类型( std::size_t )。 Assuming size_t is as big as int or bigger, i is converted to the same unsigned type before the operation is performed. 假设size_tint或更大一样大,则在执行操作之前, i将转换为相同的无符号类型。 The value i gets will be the maximum value for that type, which looks to be divisible by 3 for you. i得到的值将是该类型的最大值,它看起来可以被3整除。

问题是负数的百分比在C ++中没有明确定义。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM