尝试查找一天中经过的时间百分比。我不确定我做错了什么,但是编译和执行代码只给了我0.0而且我不确定我做错了什么。
class Time {
public static void main(String[] args) {
// variable assignments apply to the time when I started
// writing program
int hour, minute, second;
hour = 11;
minute = 8;
second = 14;
int hoursToMinutes = hour * 60;
int minutesToSeconds = (hoursToMinutes + minute) * 60;
int secondsElapsed = minutesToSeconds;
System.out.println(secondsElapsed + " seconds have elapsed.");
int secondsPerDay = 24 * 60 * 60;
double percentageOfDayElapsed = secondsElapsed / secondsPerDay;
System.out.println(secondsPerDay);
System.out.println(percentageOfDayElapsed + "% of the day has elapsed.");
}
}
答案 0 :(得分:2)
secondsElapsed / secondsPerDay
正在执行整数除法,这意味着不会返回任何小数。如果要使用带小数的除法,可以将其中一个操作数转换为double
:
double percentageOfDayElapsed = (double) secondsElapsed / secondsPerDay;
另外,因为这应该是一个百分比,我希望它乘以一百:
double percentageOfDayElapsed = ((double) secondsElapsed / secondsPerDay) * 100;
另一件事:second
变量从未使用过。也许它应该添加到secondsElapsed
:
int secondsElapsed = minutesToSeconds + second;
答案 1 :(得分:0)
int secondsElapsed = minutesToSeconds;
int secondsPerDay = 24 * 60 * 60;
你潜水两次!将它们改为双打:
double secondsElapsed = minutesToSeconds;
double secondsPerDay = 24 * 60 * 60;
然后做你的部门:
double percentageOfDayElapsed = secondsElapsed / secondsPerDay;
答案 2 :(得分:0)
问题在于您将整数除以整数。 它会给你一个小于一的数字。 因为它是一个整数,所以它将被截断为0.只有在此之后它才会被转换为double。因此,您希望在进行除法之前将其转换为双精度。
将分割线更改为:
double percentageOfDayElapsed = ((double)secondsElapsed / (double)secondsPerDay)*100;