Help converting number to Hours/Minutes/Seconds

Hi,

I'm trying to create a program in C++ that generates a random number, like 173.5 and convert it to Hours/Minutes/Seconds. So it would take 173.5 and give me 2 Hours, 53 Minutes, and 30 seconds.

The beginning is my random number generator that helps the numbers be more random. I have that working fine. What I want to get to work is the other part.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

int main()

{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
    srand(time(0));
    double rnd1, rnd2, rnd3, rnd4; 
    int hours, minutes;
    //This part works fine
    do
    {
    rnd1 = rand();
    rnd2 = (rand() % 10) + 1;
    rnd3 = (rnd1 / rnd2);
    } while(rnd3 > 14000);
    rnd4 = (rnd3 / 10);
    cout << rnd4 << endl;
    // ^ works fine
    
    //Need help here
    hours = (rnd4 / 60);
    minutes = (rnd4-(60*hours));
    
    cout << hours <<endl;
    cout << minutes <<endl;
    system("pause");
    
    
    return 0;
}

Thanks
Well I thought about it a bit more and think I got a bit closer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

int main()

{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
    srand(time(0));
    double rnd1, rnd2, rnd3, rnd4; 
    int hours, minutes, seconds;
    
    //This part works fine
    do
    {
    rnd1 = rand();
    rnd2 = (rand() % 10) + 1;
    rnd3 = (rnd1 / rnd2);
    } while(rnd3 > 14000);
    rnd4 = (rnd3 / 10);
    cout << rnd4 << endl;


    // ^ works fine
    
    //Need help here
    hours = (rnd4 / 60);
    minutes = (rnd4-(60*hours));
    seconds = (rnd4-((hours*60)+minutes))*60;
    cout << hours <<endl;
    cout << minutes <<endl;
       cout << seconds <<endl;
    system("pause");
    
    
    return 0;
}


The only problem is that sometimes the numbers are off by 1 or so.
For instance I just ran the program and the random number I received was 303.0. It then came up with 3 hours 22 minutes 58 seconds. It should be 3 hours 23 Minutes 0 seconds
I believe that has to do with rounding up/down.
Anything I can do to fix that?

Thanks


--------------------
Thought about it more and I solved the problem.
Last edited on
Topic archived. No new replies allowed.