In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
Chapter 10 // Exercise 6
Define a Roman_int class for holding Roman numerals (as ints) with a << and >>. Provide Roman_int with an as_int() member that returns the int value, so that if r is a Roman_int , we can write cout << "Roman" << r << " equals " << r.as_int() << '\n';
This exercise was quite confusing. He mentions to store the values in Roman_int as ints but then use a member function called as_int() to return the integer value of the int??? Surely it would make more sense to input the values as chars like C or M and then use the as_int() function to output 100 or 1000.
Eventually I decided upon a class that stores an int but when using cout<< it returns the roman numeral comversion. This turned out to be harder than I thought. The main problem comes from the adding/subtracting depending what side of the main number you're on. My first few attempts ended up with a lot of ifs and switches but if there's one thing I've learnt in my job as an engine programmer, it's to avoid branching as much as possible. So I scoured the internet in search of a more optimal solution.
I eventually came across this one: https://www.geeksforgeeks.org/converting-decimal-number-lying-between-1-to-3999-to-roman-numerals/
This smartly uses modulo and divide to correctly determine where the number is in the number table. For example if you input 618, the divide will be 0 for the first 2 loops (and therefore there will be nothing to print). However 618 / 500 is 1, therefore the corresponding symbol will be printed that matches the index of the table. This is what I was trying to attempt but I kept messing up the division and remainders.
.....*sometime later*
When attempting the next exercise I quickly realised that the class needed a way to convert roman numerals to ints. I thought that this would be pretty simple however there is the rule that if the following number is greater than the previous then you subtract. Numerous examples on the internet were either in Python (eurgh) or contained a great deal of branching. I'm quite proud of the small function that I came up with.
.....*sometime later*
When attempting the next exercise I quickly realised that the class needed a way to convert roman numerals to ints. I thought that this would be pretty simple however there is the rule that if the following number is greater than the previous then you subtract. Numerous examples on the internet were either in Python (eurgh) or contained a great deal of branching. I'm quite proud of the small function that I came up with.
No comments:
Post a Comment