This video is going to introduce you to a new operator called the modulus operator (%).
In the last video I gave you this example:
int y = 5 / 2;
I told you that the value of y is going to be 1. Did you figure out what this operator does? Well it actually takes the remainder. I’ve always been pretty bad at visualizing a remainder, so I use imagery. Imagine you have a pizza with 5 slices and you want to share the pizza with your pet rat, Pepper Jack.
Well you give a piece to Pepper Jack, a piece to you, a piece to pepper jack, and then another piece to you. Now, you have one left over:
int piecesOfPizza = 5;
int numberOfEaters = 2;
int leftOver = piecesOfPizza % numberOfEaters;
Now you might suggest just ripping the pizza in half, but you have to realize that piecesOfPizza is an integer. This means that we cannot split the piece in half.
This brings up the good point that the modulus operator is designed to work with integers. That’s because if you were using numbers of type double here, you and your pet rat would both get 2.5 pieces of pizza and the remainder would be zero. The modulus operator would be useless working with floating point numbers.
You can do a lot of cool things with the modulus operator. One example is figuring out if a number is even or odd. if you divide a number by 2 and the remainder is anything but 0, then you do not have an odd number.
That is all for the modulus operator. In the next video we are going to learn our first unary operator.
Subscribe to my newsletter:
Xem thêm Bài Viết:
- Bật mí cách mod thanh trạng thái android đơn giản, không cần root
- SSHD vs SSD: Các bước nâng cấp cho máy tính để bàn trên PC
- Bật mí cách tạo checkbox trong excel 2007 và một số thủ thuật đơn giản
- Cách sử dụng Excel: 18 Mẹo, Thủ thuật và Phím tắt dễ dàng trong Excel
- Hướng dẫn lắp chảo mobiTV và cách dò kênh.