我是java的新手,想知道如何将用户输入(整数)更改为十进制形式。例如,如果用户输入6作为年度兴趣,则在计算完成之前将其更改为0.06并打印答案。
此程序仅用于确定银行帐户的持续时间...但我也应该以年和月的格式打印。我不知道怎么做,除了输入另一个if语句并说if(从上面的计算回答> 12)从计算中减去12并将add1添加到年...并以某种方式将其放入循环中。
如果有人有建议/指示给予这样做,那真的很有帮助!
import java.util.*;
class Two {
public static void main(String[] args) {
Scanner imp = new Scanner(System.in);
System.out.print("Enter your initial balance: ");
double bal = imp.nextDouble();
System.out.print("Enter your yearly interest: ");
double intr = imp.nextInt();
System.out.print("Enter your monthly withdrawls: ");
double wtd = imp.nextDouble();
if (true) { //need to change
System.out.print("Your account will last " + (((bal*intr) + bal)/ wtd) + " months");
} else { System.out.print("The account will last forever");
}
}
}
答案 0 :(得分:3)
尝试
double intr = ((double)imp.nextInt()/100);
修改强>
哎呀,我错过了那个嵌套的问题。请参阅How to convert months to years-and-months。答案 1 :(得分:3)
您想要转换为百分比,因此您必须除以100.这是一个可能的解决方案:
double intrAsDouble = ((double)intr)/100;
哦,至于日期的事情:
int totalMonths = ((bal*intrAsDouble) + bal))/wtd;
int years = (int)(totalMonths/12);
int months = totalMonths%12;
String accountWillLast = "";
boolean hasMonths = months != 0;
boolean hasYears = years != 0;
if (hasYears) {
accountWillLast = accountWillLast + years;
if (years == 1) accountWillLast = accountWillLast + " year";
else accountWillLast = accountWillLast + " years";
}
if (hasMonths && hasYears) {
accountWillLast = accountWillLast + " and ";
}
if (hasMonths) {
accountWillLast = accountWillLast + months;
if (months == 1) accountWillLast = accountWillLast + " month";
else accountWillLast = accountWillLast + " months";
}
答案 2 :(得分:3)
你可以乘以0.01(这可以避免显式转换虽然从int到double的转换需要以某种方式发生)
double intr = imp.nextInt()*0.01;
并将月份转换为年+月检查整数除法和模运算符
int months = 18;//calculated
int years = month/12;//integer division is a implicitly rounded down
months = months%12;
或者如果你真的需要制作一个循环
int months = 18;//calculated
int years = 0;
while(months >= 12){
months -= 12;
years += 1;
}