convert input in seconds to days, hours, minutes in seconds from day on another planet. C code

Asked

Viewed 54 times

3

I need to convert the passage of time from another planet to days, hours, minutes and seconds on earth.

The point is, I’m getting one int (variable seg) for the seconds spent on Jupiter and I need to know how much time is spent on Earth.

dia = (seg / 35760); 
hora = (seg / 3600) - (dia * 24);
minuto = (seg % 3600) / 60;
segundo = (seg % 60); 

35760 represents the number of seconds a day on Jupiter. (9 hours 56 minutes)

The entrance is: 267547464242.

Expected output is: 7481752 days, 3 hours, 32 minutes and 2 seconds.

But the output that my code is presenting is:

7481752 days, -105243308 hours, 4 minutes, 2 seconds.

I made the same logic for other planets, and it worked, just the one that doesn’t work.

Can someone help me?

  • I think you will need to take the rest of the division, which is what is left, to calculate the other ``periods (rest of the day calculates hour, rest of the hour, calculates minute, etc). The rest operator in the javascript is percentage %. For example 267547464242 % 35760 will give 12722, or if that is what is left of the division of days, which are the hours

1 answer

3


Well, in calculating the hours that dia * 24 is the cause of the problem. As the total of days is 7481752 (over 7 million), by multiplying by 24 will be an even greater number (over 170 million), and subtract that from the total hours (which is seg / 3600, about 74 million) end up giving this result there.

I find it simpler to discount the days of the total of seconds, so it becomes simpler to calculate the hours:

dia = seg / 35760;
seg %= 35760;
hora = seg / 3600;
seg %= 3600;
minuto = seg / 60;
segundo = seg % 60;

That is, after calculating the amount of days, I do seg %= 35760, which is the same as seg = seg % 35760: the variable seg receives the rest of the seg by 35760. That is, I take only the "surplus" in seconds, which would be the same as discounting the amount of days from that total. In this case, this value is 12722.

With this I can simply divide 12722 by 3600 to get the total hours. Then I take the rest of the division by 3600 to get the "over" and divide by 60 to get the minutes. Finally, I take the rest of the division by 60 to catch the surplus in seconds.

Thus, the result will be 7481752 days, 3 hours, 32 minutes, 2 seconds.


Assuming, of course, that all variables are of some kind that support the value 267547464242 (for example, if you are using a 32-bit type, it will not support such a value).

I did the test on an Ubuntu 20 machine, with gcc 9.3.0 and only worked if use long, for the int does not support this value.

  • gave certin! thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.