I want to assign grades based on the test scores.
I know if you use switch
or if..else
statements, there will be no more than 5 statements but anyone has any better solution?
I used ASCII values to go about it but in terms of lines of code it's merely the same.
Here is the code:
Score/=10;
Score=min(9,Score);
Score=9-Score;
Score+=65;
if(Score<=68)
{
cout<<static_cast<char>(Score)<<endl;
}
else
{
cout<<"F"<<endl;
}
A standard approach in situations when the number of input choices is limited is to use a look-up table:
cout << "FFFFFFDCBAA"[Score/10];
Demo.
(from comments) could you please explain what's going on in the code?
String literal "FFFFFFDCBAA"
is treated as a const char*
pointer, which allows application of indexer []
operator. Score
is divided by ten in integers, producing a number between 0 and 10, inclusive. Eleven characters in the string correspond to letter grades of "raw" score divided by ten.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With