我应该编写一个程序来执行以下操作:
体重爱好者想要一个程序,允许用户输入一个盎司的值,然后显示吨,磅和盎司的组合,每个值按吨,磅和盎司的顺序最大化。输入值不应超过5亿盎司(500,000,000)。
输出应如下所示:
以盎司为单位输入重量:123456789
吨,磅和盎司的组合数量: 吨:3858 磅:49 盎司:5 123456789盎司= 3858吨+ 49磅+ 5盎司
除了盎司工作外,我还有其他一切。我不确定我是否正确设置这些公式或是否有更好的方法来做到这一点。非常感谢帮助。
import java.util.Scanner;
public class WeightConversion
{
public static void main (String[] args)
{
Scanner userInput = new Scanner(System.in);
int weightInOunces = 0;
int tons = 0;
int pounds = 0;
int ounces = 0;
System.out.print("Enter weight in ounces: ");
weightInOunces = userInput.nextInt();
if (weightInOunces > 500000000)
{ System.out.print("Limit of 500,000,000 ounces exceeded!");
}
else
{System.out.println ("Combined Number of Tons, Pounds, Ounces: "
+ "\n\tTons: " + weightInOunces / 32000);
tons = weightInOunces / 32000;
System.out.println ("\tPounds: " + (weightInOunces - (tons * 32000)) / 16);
pounds = tons / 2000;
System.out.println("\tOunces: " + ((weightInOunces - (tons * 32000)) - (pounds * 16) ));
ounces = pounds / 16;
}
}
答案 0 :(得分:1)
逐步增加,最低单位:
final int OUNCES_PER_POUND = 16;
final int POUNDS_PER_TON = 2000;
int value = 123456789; // value is in ounces
int ounces = value % OUNCES_PER_POUND;
value /= OUNCES_PER_POUND; // value is now in whole pounds
int pounds = value % POUNDS_PER_TON;
value /= POUNDS_PER_TON; // value is now in whole tons
int tons = value;
// prints: 3858 tons + 49 pounds + 5 ounces
System.out.printf("%d tons + %d pounds + %d ounces%n", tons, pounds, ounces);
这类似于你经常使用的时间值:
long value = 1472672270262L; // 2016-08-31 19:37:50.262 GMT
long millis = value % 1000; value /= 1000;
long seconds = value % 60; value /= 60;
long minutes = value % 60; value /= 60;
long hours = value % 24; value /= 24;
long days = value;
// prints: 17044 days + 19 hours + 37 minutes + 50 seconds + 262 millis since Jan 1, 1970 at 00:00 GMT
System.out.printf("%d days + %d hours + %d minutes + %d seconds + %d millis since Jan 1, 1970 at 00:00 GMT%n",
days, hours, minutes, seconds, millis);
答案 1 :(得分:0)
而不是
pounds = tons / 2000;
将磅设置为:
pounds = (weightInOunces - (tons * 32000)) / 16;
您也可以删除
ounces = pounds / 16;
答案 2 :(得分:0)
int tons = weightInOunces / (2000*16);
int remainingOunces = weightInOunces % (2000*16);
int pounds = remainingOunces / 16;
int ounces = remainingOunces % 16;