Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+25 votes

In class today we discussed the use of the modulus operation for int which I understand why it would be used.

What would the use of modulus for a double be if you can gain the full decimal value since it is a double?

asked in CSC211_Winter2018 by (8 points)

1 Answer

+9 votes
Best answer

Yes, you will get the full decimal value of a double if you use division as well as modulus, but the purpose of the modulus operation is to return the remainder of the number on the left after it has been divided by the number on the right.

The modulus operation has practicality for both int and double types: specifically thinking of mixing ints and doubles here, but consider a pool that has overflowed by a multiple of its total volume, measured in gallons. You can use integers to determine the volume of the pool, and you can determine the ratio between volume and total water, but what about the overflow? If you want to know exactly how much water overflowed in this situation, you would need to use the modulus operation between the total water and the volume of the pool.

Here's some sample code:

public class poolOverflow {
    public static void main(String[] args) {  
      // determine overflow of pool using modulus operation
      int volumeOfPool = 187;
      double water = volumeOfPool * 1.4;
      System.out.println("Volume of pool: " + volumeOfPool);
      System.out.println("Total water: " + water);
      System.out.println("Ratio of water to volume of pool: " + (water / volumeOfPool));
      System.out.println("Overflow: " + (water % volumeOfPool));

And here's its output:

Volume of pool: 187
Total water: 261.8
Ratio of water to volume of pool: 1.4000000000000001
Overflow: 74.80000000000001

Hope this helps!

answered by (8 points)
selected by