How do I improve on this code?
I can’t seem to find any better looking code or more readable.
If anyone knows how to make this more clean please let me know.
Any tips on how to do it in the future are well appreciated.
public IActionResult Opdracht4_5(int score)
{
var result = "";
if (score == 100 && score >= 97)
{
result = "A+";
} else if (score <= 96 && score >= 93)
{
result = "A";
} else if (score <= 92 && score >= 90)
{
result = "A-";
} else if (score <= 89 && score >= 87)
{
result = "B+";
} else if (score <= 86 && score >= 83)
{
result = "B";
} else if (score <= 82 && score >= 80)
{
result = "B-";
} else if (score <= 79 && score >= 77)
{
result = "C+";
} else if (score <= 76 && score >= 73)
{
result = "C";
} else if (score <= 72 && score >= 70)
{
result = "C-";
} else if (score <= 69 && score >= 67)
{
result = "D+";
} else if (score <= 66 && score >= 63)
{
result = "D";
} else if (score <= 62 && score >= 60)
{
result = "D-";
} else if (score < 60)
{
result = "F";
}
ViewBag.Output = result;
return View();
}
ViewBag.Output = result : Returns the result message to the front-end
3
Answers
This has fixed my issue.
Yes, you can use switch expressions for example.
This task can be accomplished much much more effective.
Just check this code:
The
_scores
array contains the maximum score to get specific grade.The
_grades
array contains grades and have one element more than_scores
array. Its crucial for the_scores
array to be sorted ascending, because of how binary search algorithm works. And finally, this approach only makes at most four comparisons to find the right grade.