Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting integers to alphabetic characters

Tags:

c++

ascii

I want to assign grades based on the test scores.

  • A for 90-100.
  • B for 80-89.
  • C for 70-79.
  • D for 60-69.
  • F for 0-59.

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;
}
like image 706
Mohsin Avatar asked Jun 25 '16 13:06

Mohsin


1 Answers

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.

like image 152
Sergey Kalinichenko Avatar answered Nov 14 '22 21:11

Sergey Kalinichenko