我正在尝试制作一个将英寸转换为英尺的程序,并返回英尺数和剩余英寸数(如果有的话)。我试过这个:
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");
}
不起作用。
有人帮我这个,拜托!谢谢。
答案 0 :(得分:2)
试试这个:
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");
}
答案 1 :(得分:2)
int inches = 34;
int feet = inches / 12;
int leftover = inches % 12;
System.out.println(feet + " feet and " + leftover + " inches");
答案 2 :(得分:0)
您的代码不起作用的主要原因是因为您正在执行
leftoverInches = inches%feet;
假设你给它13英寸。你有脚= 1(13 * 0.083向下舍入),英寸= 13%1 = 0.你的意思是
leftoverInches = inches%12;
13,13%12 = 1,这确实是剩余英寸的数量。
较小但仍然很重要的错误是你乘以0.083,这不是1/12,并且会给你严重的不准确性。例如,如果输入1,000,000英寸,您将获得
1000000 * 0.083 = 83000 feet
但是
1000000 / 12 = 83333 feet rounded down
所以你会有333英尺的距离。