Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <map>
- #include <cfloat>
- #include <sstream>
- typedef std::map< double, std::string > GradeTranslationMap;
- template < class T >
- T
- promptForValue
- (
- const std::string & promptStr
- )
- {
- T value = 0;
- std::cout << promptStr << " : ";
- std::cin >> value;
- return value;
- };
- GradeTranslationMap
- generateRatioToGradeMap
- ()
- {
- GradeTranslationMap xlator;
- xlator[ 0.6 - DBL_EPSILON ] = "F";
- xlator[ 0.7 - DBL_EPSILON ] = "D";
- xlator[ 0.8 - DBL_EPSILON ] = "C";
- xlator[ 0.9 - DBL_EPSILON ] = "B";
- xlator[ 1.0 ] = "A";
- xlator[ DBL_MAX ] = "A+";
- return xlator;
- }
- /*
- \brief Returns the ratio of the mark.
- */
- double
- grader
- (
- double grade,
- double total
- )
- {
- //Sanity checks
- if ( grade < 0 ) throw std::string( "Negative grades are invalid." );
- if ( total <=0 ) throw std::string( "Negative or null totals are invalid" );
- //Calculate the grade as a percent, and print to cout
- double ratio ( grade / total );
- double percent ( ratio * 100.0 );
- std::cout << percent << "%";
- //Determine the alphabetic grade too:
- /*
- Here is some magic: We build a lookup table to convert ratios to grades,
- instead of using a messy if else if death-trap.
- Also, making it static const is like declaring a global variable. But without
- poluting the global namespace.
- */
- static const GradeTranslationMap XLATE_RATIO_TO_GRADE( generateRatioToGradeMap() );
- /*
- The STL is our friend. Make use of it. look up what std::map lower_bound does
- */
- GradeTranslationMap::const_iterator gradeIt = XLATE_RATIO_TO_GRADE.lower_bound( ratio );
- if ( gradeIt == XLATE_RATIO_TO_GRADE.end() ) throw std::string( "No string grade found." );
- std::cout << ", or, also a " <<gradeIt->second << std::endl;
- //rerturn the grade ratio
- return ratio;
- }
- int
- main()
- {
- //How many people play?
- int players ( promptForValue<int>( "Number of players" ) );
- double outOf ( promptForValue<double>( "What was the test out of" ) );
- std::cout << std::endl;
- double totalRatio = 0;
- double validRatios = 0;
- for ( int p = 1; p <= players; p++ )
- {
- try
- {
- //Fetch the garde info
- std::stringstream promptMessage;
- promptMessage << "Enter player " << p << "'s grade";
- std::string promptMsg( promptMessage.str() );
- //calculate the grade, out of 1.
- double grade ( promptForValue<double>( promptMsg ) );
- //Now issue a grade
- double ratio ( grader( grade, outOf ) );
- //Also, keep track of the marks so far.
- totalRatio += ratio;
- validRatios++;
- }
- catch ( const std::string & error )
- {
- std::cout << "Error: " << error << std::endl;
- }
- }
- //Display infor about the overall performance too
- if ( validRatios > 0 )
- {
- std::cout << std::endl << "Overall grade: ";
- grader( totalRatio, validRatios );
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment