-1

I want you to figure the mistake I am doing. suppose I'm taking distance=300 and speed=80 then I should get the answer as 3 hours 44 minutes and 27n seconds, but I'm not getting that, instead I'm getting 3 hours 45 min and 2700 sec. please resolve my issue.

#include <stdio.h>

int main()
{
    //calculate the time taken to reach from city A to city B.
    int distance, speed;
    int time, D;
    float speedInMinutes;
    int TimeInMinutes;
    float speedInSec, TimeInSec;
    printf("Distance between the two cities A and B= ");// unit- Km
    scanf("%d", &distance);
    printf("Speed of the car= ");// unit- km/h
    scanf("%d", &speed);
    time=distance/speed;// unit- hr
    speedInMinutes=speed/60.0;
    TimeInMinutes=(distance%speed)/speedInMinutes;
    speedInSec=speed/3600.0;
    TimeInSec=(distance%speed)/speedInSec;
    printf("Time taken by the card to reach city B from city A= %d hours %d minutes %0.0f sec\n", time, TimeInMinutes, TimeInSec);
    return 0;
}
001
  • 13,291
  • 5
  • 35
  • 66
  • 1
    I would make time a float (or typically you can use double everywhere float appears for more accuracy). – JosephDoggie Jan 10 '23 at 14:42
  • 2
    `time=distance/speed;` You are doing integer division here. So, for example, if `distance = 300` and `speed = 80` then `time` will be `3` and not `3.75` – 001 Jan 10 '23 at 14:48
  • 1
    `time` should be `float` or `double` and `distance/speed;` should be `(float)distance/speed;` or `(double)distance/speed;` because `distance/speed` is an integer division. – Jabberwocky Jan 10 '23 at 14:49

1 Answers1

2

suppose I'm taking distance=300 and speed=80 then I should get the answer as 3 hours 44 minutes and 27n second

no. 300/80 = 3.75 = 3 hours, 45minutes and 0 seconds.

void printTime(double distance, double speedKMH)
{
    double time = distance / speedKMH;
    unsigned seconds = (time - (unsigned)time) * 3600;

    printf("%u:%02u:%02u\n", (unsigned)time, seconds / 60, seconds % 60);
}

int main(void)
{
    printTime(300.0, 80.0);
}
0___________
  • 60,014
  • 4
  • 34
  • 74