Tugger the SLUGger!SLUG Mailing List Archives

Re: [coders] RubySIG Lesson Code


On Wed, Jun 14, 2006 at 12:22:09AM +1000, Benno wrote:
> 
> And now for the C version
> 

Here's a C++/boost version:

#include <iostream>
#include <cmath>
#include <boost/lexical_cast.hpp>

using namespace std;

int
main(int argc, char **argv)
{
        float amount = boost::lexical_cast<float>(argv[1]);
        float remainder = fmodf(amount, 5.0);
        float base_amount = amount - remainder;
        float x;

        if (remainder > 2) {
                x = 5;
        } else {
                x = 0;
        }

        cout << base_amount + x << endl;

        return 0;
}


Notes:
1. easy to write as I just made small changes to Benno's C version :-)
2. only interesting things over C is the boost::lexical_cast
   and perhaps the cout line. lexical_cast will throw an exception and
   print out an ugly error should you dare to supply it with non-numeric.
3. noticeably less clean than ruby or python
4. would take someone a fair bit of googling/experience to even
   know about boost lexical_cast!
5. doesn't need stdlib as it doesn't use atof
6. binary about twice as big as the C version's
7. didn't demand to be linked with the maths library (-lm); I don't know why!
8. doesn't segfault if not given enough args (I know this wasn't in the spec tho')

Of course, the C version is also a C++ version; you don't
have to use boost, iostreams....


Regards,
Matt