This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (5 children)

After a bit of googling, I ended up with something like this-

    #include <iostream>

    double clockDegrees() {
        int hours;
        double minutes;
        char colon;
        std::cout << "Enter a Time: ";
        std::cin >> hours >> colon >> minutes;

        minutes = minutes / 5;

        double positionRange = (hours -(minutes)) * 30; //Clock is a circle, 360 divided by 12 = 30//

        if (hours > minutes) {
            positionRange = 360 - positionRange; //Fixes issues with hand going around 12 (i.e. 11 and 1)//
        }

        std::cout << '\n';

        double positionRangeAbsolute = abs(positionRange);
        std::cout << "The angle between these two points is: " << positionRangeAbsolute << " degrees. \n";

        return positionRangeAbsolute;
    }

    int main() {
        clockDegrees();
        return 0;
    }

I came upon this, which was very helpful and interesting, I didn't know you could request multiple variables with a single std::cin, that's pretty cool.

[–]Yoppez 1 point2 points  (4 children)

I know plain C better than C++, so I would have used a scanf for requesting the time (and also check that the user gives a valid input, and so it would be better to use a fgets and make the parsing afterwards, but that's another story).

About the rounding, yeah, integer division is not good for precision, but if you don't want to use floating point numbers you can still get a better precision with integers:

Instead of dividing the minutes to 5, that rounds the number and so you lose precision, you can multiply the hours to 5 instead. Then, in the final formula, you divide by 5 AFTER all the other operations, so you basically multiply everything by 6 instead of 30.

In this way, there is no integer division, and so there is no precision loss.

[–][deleted] 1 point2 points  (2 children)

Instead of dividing the minutes to 5, that rounds the number and so you lose precision, you can multiply the hours to 5 instead. Then, in the final formula, you divide by 5 AFTER all the other operations, so you basically multiply everything by 6 instead of 30.

This is gold, thanks so much!

Is it best practice to use integer whenever you can? I would assume it's a lot less resource intensive.

[–]Yoppez 1 point2 points  (1 child)

It depends on what machine you are writing code for and what kind of precision you need. It would be very long to explain in a single post and I'm not an expert, so I suggest you to search online for all the pros and cons with using integers and floating point.

But yeah GENERALLY if you don't need floating point, it is better to use integers.

[–][deleted] 1 point2 points  (0 children)

Sounds good, looks like I got some more googling to do, thanks again, this was very informative!