java 将英尺转换为英寸
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5424350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert feet to inches
提问by tekman22
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.
有人帮我解决这个问题,请!谢谢你。
回答by WhiteFang34
int inches = 34;
int feet = inches / 12;
int leftover = inches % 12;
System.out.println(feet + " feet and " + leftover + " inches");
回答by Naftali aka Neal
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");
}
回答by donnyton
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
假设你给它 13 英寸。你会有英尺 = 1(13 * 0.083 向下舍入),英寸 = 13 % 1 = 0。你的意思是
leftoverInches = inches%12;
With 13, 13%12 = 1, which is indeed the number of leftover inches.
有了13,13%12=1,这确实是剩下的英寸数。
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
一个较小但仍然重要的错误是您乘以 0.083,这不是 1/12,并且会给您带来严重的不准确。例如,如果您输入 1,000,000 英寸,您将得到
1000000 * 0.083 = 83000 feet
But
但
1000000 / 12 = 83333 feet rounded down
So you would be 333 feet off.
所以你会离开 333 英尺。