I have included my code below, Trying to take a speed from the user and a Distance they need to travel and calculate how many hours and minutes the trip will take.
But my minutes keep on displaying 0, I get the correct leftover from the modulus operator in the Temp variable. Is it something to do with casting/type of variables maybe?
I hope someone that is a bit better than me can see the fault.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Initialise 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 arrive in %d hours and %d minutes\n",
Distance, Speed, Hours, Minutes);
return 0;
}
Tried to change the types and cast some variables differently, but just keeps on delivering 0.
OP's approach determines
Hours, Minutesindependently fromDistanceandSpeedand incurs edge and coherency issues./ 100makes little sense.Avoid residual and rounding issues by moving the
Hours, Minutescalculations both from an integer derived from the same single FP value.Here,
Hours, Minutesform a common single quantity calledTotalwhich is the total time in minutes and bypasses the/ 100mistake.Also,
Total = lround(60.0 * Distance / Speed)useslround()as the time sought is likely better rounded to the nearest minute rather than truncated.Simply as: