将模余数转换为分钟

问题描述 投票:0回答:1

我在下面添加了我的代码,尝试从用户那里获取速度和他们需要行驶的距离,并计算行程需要多少小时和分钟。

但是我的分钟数继续显示 0,我从 Temp 变量中的模运算符得到了正确的剩余值。这可能与变量的转换/类型有关吗?

我希望比我好一点的人能看到错误。

#include <stdio.h>
#include <stdlib.h>

int main()
{
//Intialise the variables we will use
float Speed, Distance, Remainder = 0.0;
int Hours, Minutes, Temp = 0;

//Tell the user what the program does
printf("This program will take a distance and a speed and calculate your driving time!\n");

//Take user input
printf("please enter the speed you are driving at: ");
scanf("%f", &Speed);

printf("Enter the distance you will travel: ");
scanf("%f", &Distance);

//calculate the result`your text`
Hours = Distance / Speed;   
Temp = (int)Distance % (int)Speed;
printf("temp = %d\n", Temp);
Minutes = (Temp / 100) * 60;

//Print out the result
printf("If you are traveling %.2f km at the speed %.2f km/h you will arive in %d hours and %d minutes\n", Distance, Speed, Hours, Minutes);


    return 0;
}

尝试更改类型并以不同方式转换一些变量,但只是继续提供 0。

c casting datetime-conversion
1个回答
0
投票

首先将

hours, minutes
移至整数数学中来避免残差和舍入问题

long both = lround(60 * Distance / Speed);
Hours = both / 60;
Minutes = both % 60;
© www.soinside.com 2019 - 2024. All rights reserved.