我是新的,标准的开始,所以我会把剩下的都留下来。 我是否必须将每个int转换为秒,或者这是对的吗? 因为当我向后计算,手动并计算最终语句的秒数时,我会得到几小时的差异。
Thx Casu
Scanner input = new Scanner(System.in);
final int secmin = 60;
final int day = 24;
final int year = 365;
int seconds = input.nextInt();
int minutes = seconds / secmin;
int remainSec = seconds % secmin ;
int hours = minutes / secmin;
int remainMin = hours % secmin;
int days = hours / day;
int remainHours = hours % day;
int years = days / year;
int remainDays = days % year;
if (minutes <= 59)
{
System.out.println(seconds + " seconds is " + minutes +" minutes and " + remainSec + " seconds");
}
else if (hours <= 23)
{
System.out.println(seconds + " seconds is " + hours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else if (days <= 364)
{
System.out.println(seconds + " seconds is " + days + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else
{
System.out.println(seconds + " seconds is " + years + " years " + remainDays + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
答案 0 :(得分:1)
我认为这个陈述需要改变: 来自&#34; int remainingMin =小时%sec min;&#34;
到&#34; int remainingMin =分钟%secmin;&#34;。
休息一下看起来不错。
答案 1 :(得分:0)
代码看起来不错。但是,我会删除&#34; Magic Numbers&#34;来自if语句:
Scanner input = new Scanner(System.in);
final int secmin = 60;
final int day = 24;
final int year = 365;
int seconds = input.nextInt();
int minutes = seconds / secmin;
int remainSec = seconds % secmin ;
int hours = minutes / secmin;
int remainMin = hours % secmin;
int days = hours / day;
int remainHours = hours % day;
int years = days / year;
int remainDays = days % year;
if (minutes < secMin)
{
System.out.println(seconds + " seconds is " + minutes +" minutes and " + remainSec + " seconds");
}
else if (hours < day)
{
System.out.println(seconds + " seconds is " + hours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else if (days < year)
{
System.out.println(seconds + " seconds is " + days + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else
{
System.out.println(seconds + " seconds is " + years + " years " + remainDays + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
我知道年/日/小时/分钟/秒的比例都是非常静态的,但是如果有人想要在10秒到10分钟到10小时之间看到你的代码呢?然后你只需要换一个地方而不是两个。
在生产应用程序中,这可能会增长到代码中的数百个位置,并且很难追逐每一个位置。
答案 2 :(得分:0)
我确实输了=
1234234234 s
输出=
1234234234秒是39年50天2小时2分34秒
和=
1229904000 s + 4320000 s + 7200 s + 120 s + 34 s = 1234231354 s
差异=
2880 s
当我改变时:
int remainingMin =小时%secmin; “to”int remainingMin = minutes%secmin;
然后:
1234234234秒是39年50天2小时50分34秒
结果:
48分钟添加
1229904000 s + 4320000 s + 7200 s + 3000 s + 34 s = 1234234234 s
,差异为0。
感谢您更正用户2006544和改进史蒂夫。