模运算符如何工作? [英] How does the modulus operator work?

查看:123
本文介绍了模运算符如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要格式化数组的输出,以便每行显示固定数量的元素。我如何使用模数运算?

Let's say that I need to format the output of an array to display a fixed number of elements per line. How do I go about doing that using modulus operation?

使用C ++,下面的代码每行显示6个元素,但我不知道如何和为什么它的工作原理?

Using C++, the code below works for displaying 6 elements per line but I have no idea how and why it works?

for ( count = 0 ; count < size ; count++)
{
    cout << somearray[count];
    if( count % 6 == 5) cout << endl;
}

如果我想要每行显示5个元素怎么办?如何在C ++表达式中找到所需的确切表达式?

What if I want to display 5 elements per line? How do i find the exact expression needed?

推荐答案

a%b 返回a除以b的余数(如果它们是正的,对于负数,结果的符号是实现定义的)。例如:

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

5 % 2 = 1
13 % 5 = 3

有了这些知识,我们可以尝试理解你的代码。条件 count%6 == 5 表示当除以6的余数为5时,将写入换行符。这是多久发生一次?正确的6行(练习:写数字1..30,下划线满足这个条件),从第6行开始(计数= 5)。

With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

要从代码中获得所需的行为,应该将条件更改为 count%5 == 4 ,从第5行开始,每5行将有一行换行= 4)。

To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

这篇关于模运算符如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆