I am trying to get a switch statement to use a variable called "avg" for the average of five grades. The five grades are added together to get the total and then divided by five to get the average. Like this:
avg = +grade_one + +grade_two + +grade_three + +grade_four + +grade_five;
The switch needs to display five cases, one for each grade range, (i.e 90% to 100% = A). As well as the percentage itself.
I have tried using cases with numeric values like "case 1" for example, and then printing two lines of text but that won't work.
Should I try using an if-else structure before the switch to establish what each grade percentage equals in a letter, or will that not work?
Here is the code for the switch.
switch (avg)
{
case 1:
letter = "A";
per = "90-100";
document.write("Based on your semester average, your grade
falls between " + per + "%");
document.write("you earned a " + letter);
break;
case 2:
letter = "B";
per = "80-89.9";
document.write("Based on your semester average your grade falls between " + per + "%");
document.write("you earned a " + letter);
break;
case 3:
letter = "A";
per = "70-79.9";
document.write("Based on your semester average your grade falls between " + per + "%");
document.write("you earned a " + letter);
break;
case 4:
letter = "D";
per = "60-69.9";
document.write("Based on your semester average your grade falls between " + per + "%");
document.write("you earned a " + letter);
break;
case 5:
letter = "F";
per = "Below 60%";
document.write("Based on your semester average your grade falls between " + per + "%");
document.write("you earned a " + letter);
default:
document.write("Invalid Entry");
break;
}
You should not use a
switchfor that: the code for each case is too similar. The difference is just in a few values, which you can store in an array. Then find in that array in which segment the average falls, and build the output from that.Also, don't use
document.writefor this. Instead create an element (like adiv) that will contain the output message.I don't know what the context is of your exercise, but I suppose there are some inputs with the 5 grades. Load those as an array (not as 5 distinct variables), and calculate the average in a generic way (not tied to 5).
Here is some suggested code in a runnable snippet: