我怎样才能去掉分数?(不知怎么的,这个分数仍然存在)



我正在尝试制作一个"距离&"速度到时间";但是分数阻碍了我计算微小部分。喜欢小时部分在某个地方仍然有一个分数值。

这就是我想要的。

在本例中,距离为130公里,速度为40公里/小时

我想要的答案是

3 Hour(s) 15 Minute(s) 0 Second(s)

但我得到的是

3 Hour(s) **0 Minute(s) 0 Second(s)**

float Bx = 130;
float By = 40;
int x = (int) Bx;
int y = (int) By;
var KeepSecond = (x / y * 3600) ;
var HourX = KeepSecond/3600;
int Hour = (int) HourX;
var MinuteX = (KeepSecond-(Hour*3600))/60;
int Minute = (int) MinuteX;
var SecondX = (KeepSecond-(Hour*3600)-(Minute*60));
int Second = (int) SecondX;
String result = String.format(Hour+" Hour(s) "+Minute+" Minute(s) "+Second+" Second(s) ");
Answer.setText(result);

您正在对distance/speed进行int除法:130/40给出3,int类型为

您需要130.0/40.0的二重或浮点除法,从而得到预期的3.25

var KeepSecond = (Bx / By * 3600);

还使用含义完整的变量名,并遵循Java约定,该约定是变量的lowerCamelCase(类名的UpperCamelCase(

float distance = 130;
float speed = 40;
var keepSecond = (distance / speed * 3600);
int hourInt = (int) keepSecond / 3600;
int minuteInt = (int) (keepSecond - (hourInt * 3600)) / 60;
int secondInt = (int) (keepSecond - (hourInt * 3600) - (minuteInt * 60));

问题出在ints的中间转换上。

在删除int x = (int) Bx; int y = (int) By;的同时,我会让代码变得更清晰和[传统上]正确,如下所示:

float distance = 130f;
float speed = 40f;
int secondsInMinute = 60;
int minutesInHour = 60;
int secondsInHour = minutesInHour * secondsInMinute;
int timeInSeconds = (int) (distance / speed * secondsInHour); // formula: t = d/s
int hours = timeInSeconds / secondsInHour;
int minutes = (timeInSeconds - (hours * secondsInHour)) / secondsInMinute;
int seconds = timeInSeconds - ((hours * secondsInHour) + (minutes * secondsInMinute));
String result = String.format("%d Hour(s) %d Minute(s) %d Second(s)", hours, minutes, seconds);
Answer.setText(result);

相关内容

最新更新