% 运算符在 N % 2 中的 Ruby 中做什么? [英] What does the % operator do in Ruby in N % 2?

查看:26
本文介绍了% 运算符在 N % 2 中的 Ruby 中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if counter % 2 == 1 我正在尝试解码这一行 - 这是一个 Rails 项目,我试图弄清楚 % 在这个 if 中做了什么声明.

if counter % 2 == 1 I am trying to decode this line - it's a Rails project and I am trying to figure out what the % does in this if statement.

推荐答案

% 运算符.counter % 2的结果是counter/2的余数.

% is the modulo operator. The result of counter % 2 is the remainder of counter / 2.

n % 2 通常是确定数字 n 是偶数还是奇数的好方法.如果n % 2 == 0,则该数为偶数(因为没有余数意味着该数可以被2整除);如果 n % 2 == 1,则数字为奇数.

n % 2 is often a good way of determining if a number n is even or odd. If n % 2 == 0, the number is even (because no remainder means that the number is evenly divisible by 2); if n % 2 == 1, the number is odd.

这篇关于% 运算符在 N % 2 中的 Ruby 中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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