I wrote a program for an assignment to calculate journey times. There is a problem since sometimes (not allways) the journey time returned is 1 off what its meant to be. I tried several different things but cnat seem to find why
Also a friend of mine said that theres a way to turn a float input by scanf into two seperate integers. EG: 23.45 becomes 23 and 45. If its possible could someone let me know haw that would be done, it would have made this prog a bit simpler.Code:#include <stdio.h> #include <conio.h> /*TASK 5: JOURNEY TIMES*/ int main() { //-------------------- DECLARE VARIABLES --------------------------------------// float departure_time, arrival_time; int departure_hours, departure_minutes; int arrival_hours, arrival_minutes; int duration_hours, duration_minutes; //---------------------- MAIN PROGRAM -----------------------------------------// printf("--- CALCULATIONS BASED ON A 24 HOUR CLOCK ---\n"); //Enter departure time printf("Enter the departure time of your train: "); scanf("%f", & departure_time); departure_hours = departure_time; //Copy the float to an int to floor its value //Validate departure time based on a 24hr clock while (departure_time - departure_hours > 0.59 || departure_time < 0 || departure_hours > 24 || (departure_hours == 24 && departure_time - departure_hours > 0)) { printf("Invalid. Re-enter the departure time of your train: "); scanf("%f", & departure_time); departure_hours = departure_time; } departure_minutes = (departure_time - departure_hours)*100; //Multiply out remaining minutes so they can be stored as an integer //Enter arrival time printf("Enter the arrival time of the train: "); scanf("%f", & arrival_time); arrival_hours = arrival_time; //Validate arrival time based on a 24hr clock while (arrival_time - arrival_hours > 0.59 || arrival_time < 0 || arrival_hours > 24 || (arrival_hours == 24 && arrival_time - arrival_hours > 0)) { printf("Invalid. Re-enter the arrival time of your train: "); scanf("%f", & arrival_time); arrival_hours = arrival_time; } arrival_minutes = (arrival_time - arrival_hours)*100; duration_minutes = arrival_minutes - departure_minutes; //Calculate journey time //If there is going to be a negative number of minutes if (duration_minutes < 0) { duration_minutes = 60 + duration_minutes; //invert minutes on a range of 60 arrival_hours = arrival_hours - 1; //the journey will now take one less hour } duration_hours = arrival_hours - departure_hours; //If the journey travels through midnight if (duration_hours < 0) duration_hours = 24 + duration_hours; //invert hours on a scale of 24 //Display journey time printf("The journey will take %i hours and %i minutes", duration_hours, duration_minutes); getchar(); getchar(); return 0; }



LinkBack URL
About LinkBacks



