Reputation: 233
I'm trying to make a program that converts inches to feet, and returns the number of feet and the number of leftover inches if any. I tried this:
public class Convertor
{
/**
* Fields
*/
private int inches;
private int feet;
private int yards;
private int leftoverInches;
/**
* Constructor for objects of class Convertor
*/
public Convertor()
{
inches=0;
feet=0;
yards=0;
leftoverInches=0;
}
/**
* Mutator method to convert inches to feet
*/
public void convertValuesInchtoFeet(int anyInches)
{
inches=anyInches;
feet=(anyInches * 0.083);
leftoverInches= inches%feet;
System.out.println(inches+" inches = " +feet+" feet.");
System.out.println("There are " +leftoverinches +" leftover inches");
}
Doesn't work.
Someone help me on this, please! Thank you.
Upvotes: 0
Views: 19589
Reputation: 6054
The primary reason your code doesn't work is because you're doing
leftoverInches = inches%feet;
Suppose you gave it 13 inches. You would have feet = 1 (13 * 0.083 rounded down), and inches = 13 % 1 = 0. What you mean to do was
leftoverInches = inches%12;
With 13, 13%12 = 1, which is indeed the number of leftover inches.
A smaller but still important error is that you multiply by 0.083, which is NOT 1/12, and will give you serious inaccuracies. For example, if you enter 1,000,000 inches, you will get
1000000 * 0.083 = 83000 feet
But
1000000 / 12 = 83333 feet rounded down
So you would be 333 feet off.
Upvotes: 0
Reputation: 146300
try this:
public void convertValuesInchtoFeet(int anyInches)
{
inches = anyInches;
feet = Math.floor(inches/12);
//if int than no need for the Math.floor()
leftoverInches = inches%12;
System.out.println(inches + " inches = " + feet + " feet.");
System.out.println("There are " + leftoverInches + " leftover inches");
}
Upvotes: 2
Reputation: 72039
int inches = 34;
int feet = inches / 12;
int leftover = inches % 12;
System.out.println(feet + " feet and " + leftover + " inches");
Upvotes: 3