Using JS i need to create a Average variable - javascript

hi i need to create a Average variable that will average out my grades any help will be greatly appreciated i have the following. but i cant figure out the average portion of it
my code works for the inputs and gets the grades, and i also have the html portion
and i have an empty p tag for all of the inner html
function myFunction(){
let math = document.getElementById("math").value;
let science = document.getElementById("science").value;
let history = document.getElementById("history").value;
let english = document.getElementById("english").value;
let average = ( [ "math","science","history","english", ] );
// this is match sec
if(math >= 90) {
document.getElementById("mathG").innerHTML = "Your Grade is A"
}
else if (math >= 80 && math < 90) {
document.getElementById("mathG").innerHTML = "Your Grade is B"
}
else if (math >= 70 && math < 80) {
document.getElementById("mathG").innerHTML = "Your Grade is c"
}
else if (math >= 60 && math < 70) {
document.getElementById("mathG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("mathG").innerHTML = "Your Grade is F"
}
// Science section
if(science >= 90) {
document.getElementById("scienceG").innerHTML = "Your Grade is A"
}
else if (science >= 80 && science < 90) {
document.getElementById("scienceG").innerHTML = "Your Grade is B"
}
else if (science >= 70 && science < 80) {
document.getElementById("scienceG").innerHTML = "Your Grade is c"
}
else if (science >= 60 && science < 70) {
document.getElementById("scienceG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("scienceG").innerHTML = "Your Grade is F"
}
// History
if(history >= 90) {
document.getElementById("historyG").innerHTML = "Your Grade is A"
}
else if (history >= 80 && history < 90) {
document.getElementById("historyG").innerHTML = "Your Grade is B"
}
else if (history >= 70 && history < 80) {
document.getElementById("historyG").innerHTML = "Your Grade is c"
}
else if (history >= 60 && history < 70) {
document.getElementById("historyG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("historyG").innerHTML = "Your Grade is F"
}
//English
english
if(english >= 90) {
document.getElementById("englishG").innerHTML = "Your Grade is A"
}
else if (english >= 80 && english < 90) {
document.getElementById("englishG").innerHTML = "Your Grade is B"
}
else if (english >= 70 && english < 80) {
document.getElementById("englishG").innerHTML = "Your Grade is c"
}
else if (english >= 60 && english < 70) {
document.getElementById("englishG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("englishG").innerHTML = "Your Grade is F"
}

The code will be like this I guess :
let average = math + science + history + english / 4;
Here you will get the average and with the if else like you did for getting grades for each subject you can find the average grade as well.
if(average >= 90) {
average = "A";
}
Tip: You can use loop or map to reduce the line of code.

A few things:
First, make sure to cast your inputs to a number. It works with strings when doing a comparison with > or <, but if you try to add strings together with +, it will concatenate them rather then summing their numeric values.
Second, you can shorten your code by putting the duplicated if/else chains into a function.
Anyway, an average is just a sum divided by the number of summed items, so:
let average = (math + science + history + english) / 4;
would work. Or you can use a reduce if you have them in an array. This might come in handy if you frequently add or remove subjects:
let scores = [math, science, history, english];
let average = scores.reduce((total, score) => total + score) / scores.length;
Anyway, here's a snippet that seems to be working how you want:
function calculateAllGrades() {
let math = Number(document.getElementById("math").value);
let science = Number(document.getElementById("science").value);
let history = Number(document.getElementById("history").value);
let english = Number(document.getElementById("english").value);
// let average = ( [ "math","science","history","english", ] );
// Hardcoded, okay if these are all subjects:
let average = (math + science + history + english) / 4;
// Or if they change, you can use an array, easier if they change or you add more:
let scores = [math, science, history, english]
average = scores.reduce((sum, score) => sum + score) / scores.length
function calculateGrade(score, elementID) {
const element = document.getElementById(elementID);
if (score >= 90) {
element.innerHTML = "Your Grade is A";
} else if (score >= 80) {
element.innerHTML = "Your Grade is B";
} else if (score >= 70) {
element.innerHTML = "Your Grade is C";
} else if (score >= 60) {
element.innerHTML = "Your Grade is D";
} else {
element.innerHTML = "Your Grade is F";
}
}
calculateGrade(math, "mathG")
calculateGrade(science, "scienceG")
calculateGrade(history, "historyG")
calculateGrade(english, "englishG")
calculateGrade(average, "averageG")
}
let button = document.getElementById("button")
button.addEventListener("click", calculateAllGrades)
<div>MATH:<input type="text" id="math" /></div>
<div>SCIENCE:<input type="text" id="science" /></div>
<div>HISTORY:<input type="text" id="history" /></div>
<div>ENGLISH:<input type="text" id="english" /></div>
<br />
<div>MATH:<div id="mathG"></div></div><br/>
<div>SCIENCE:<div id="scienceG"></div></div><br/>
<div>HISTORY:<div id="historyG"></div></div><br/>
<div>ENGLISH:<div id="englishG"></div></div><br/>
<div>AVERAGE:<div id="averageG"></div></div><br/>
<button id="button">Calculate</button>

history is a global in browsers, so you can't use it as a variable name.
You should do something like:
let mathGrade = document.getElementById("math").value;
let scienceGrade = document.getElementById("science").value;
let historyGrade = document.getElementById("history").value;
let englishGrade = document.getElementById("english").value;
let average = (mathGrade + scienceGrade + historyGrade + englishGrade) / 4
Then, if you want the 'average' letter grade, you can do something similar to what you did for the other grades using the average:
if(average >= 90) {
document.getElementById("averageG").innerHTML = "Your Average Grade is A"
}
else if (average >= 80 && average < 90) {
document.getElementById("averageG").innerHTML = "Your Average Grade is B"
}
else if (average >= 70 && average < 80) {
document.getElementById("averageG").innerHTML = "Your Average Grade is c"
}
else if (average >= 60 && average < 70) {
document.getElementById("averageG").innerHTML = "Your Average Grade is d"
}
else {
document.getElementById("averageG").innerHTML = "Your Average Grade is F"
}

Related

Finding the grade based on the best score

So my program wants the user to input the number of students and their scores. Based on the best score it will follow this grading scheme:
The score is > or = the best - 10 then the grade is A.
The score is > or = the best - 20 then the grade is B.
The score is > or = the best - 30 then the grade is C.
The score is > or = the best - 40 then the grade is D.
Anything else is an F
This is my code so far:
var readlineSync = require('readline-sync')
let scoreArray = []
let best = 0
students = readlineSync.question('Enter the number of students: ');
for (var x = 0; x < students; x++){
score = readlineSync.question('Enter Score: ')
scoreArray.push(score);
}
for (var i = 0; i < scoreArray.length; i++){
var data = scoreArray[i];
if(best < scoreArray[i]){
best = scoreArray[i];
}
if(scoreArray[i] >= (best-10)){
grade = 'A';
}else if(scoreArray[i] >= (best-20)){
grade = 'B';
}else if(scoreArray[i] >= (best-30)){
grade = 'C';
}else if(scoreArray[i] >= (best-40)){
grade = 'D';
}else {
grade = 'F';
}
console.log('Student ' + i + ' score is ' + scoreArray[i] +' and grade is ' + grade);
}
When I run the code it sometimes displays the correct grade and sometimes it doesn't. It should display this:
Enter the number of students: 4
Enter Score: 40
Enter Score: 55
Enter Score: 70
Enter Score: 58
Student 0 score is 40 and grade is C. Student 1 score is 55 and grade
is B. Student 2 score is 70 and grade is A. Student 3 score is 58 and
grade is B.
Instead it displays the grades A,A,A,B.
It looks like you're iterating over scoreArray and updating best along the way. You should first get the max score from scoreArray so you know the best to start with, and then iterate over scoreArray. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max for more info, but put var best = Math.max(...scoreArray); before your for loop, and then your conditional logic should work.
scoreArray = [49, 81, 72, 80, 81, 36, 58];
var best = Math.max(...scoreArray);
for (var i = 0; i < scoreArray.length; i++) {
var data = scoreArray[i];
if (scoreArray[i] >= (best - 10)) {
grade = 'A';
} else if (scoreArray[i] >= (best - 20)) {
grade = 'B';
} else if (scoreArray[i] >= (best - 30)) {
grade = 'C';
} else if (scoreArray[i] >= (best - 40)) {
grade = 'D';
} else {
grade = 'F';
}
console.log('Student ' + i + ' score is ' + scoreArray[i] + ' and grade is ' + grade);
}

Creating an input form with javascript

I had a question about creating a form that I can input "grades" into which also would check to see if those grades were between 0 and 25 or 0 and 100 (input validation). My code has to be in javascript but I don't know where or how to start. In other words, I need to take this code and add a "form" and check for valid input. This is what I have so far:
<!doctype html>
<html>
<script>
var a1=parseFloat(prompt("Enter the grade for assignment 1: "));
var a2=parseFloat(prompt("Enter the grade for assignment 2: "));
var a3=parseFloat(prompt("Enter the grade for assignment 3: "));
var a4=parseFloat(prompt("Enter the grade for assignment 4: "));
var mid=parseFloat(prompt("Enter the grade for the mid exam: "));
var fe=parseFloat(prompt("Enter the grade for the final exam: "));
var fp=parseFloat(prompt("Enter the grade for the final project: "));
var sum;
var grade;
var error;
sum=((a1+a2+a3+a4)/4)*(4*0.25)+(mid*0.25)+(fe*0.25)+(fp*0.25);
/* if (a1 < 0 && a1 > 25) {
error = window.prompt( "Assignments are only out of 25 points, please re-enter the integer grade:")
} */
if (sum >= 94.0) {
grade = "A";
} else if (sum <= 94.0 && sum >= 90.0) {
grade = "A-";
} else if (sum <= 90.0 && sum >= 87.0) {
grade = "B+";
} else if (sum <= 86.9 && sum >= 84.0) {
grade = "B";
} else if (sum <= 83.9 && sum >= 80.0) {
grade = "B-";
} else if (sum <= 79.9 && sum >= 77.0) {
grade = "C+";
} else if (sum <= 76.9 && sum >= 74.0) {
grade = "C";
} else if (sum <= 73.9 && sum >= 70.0) {
grade = "C-";
} else if (sum <= 69.9 && sum >= 67.0) {
grade = "D+";
} else if (sum <= 66.9 && sum >= 64.0) {
grade = "D";
} else if (sum <= 63.9 && sum >= 60.0) {
grade = "D-";
} else if (sum <= 60.0) {
grade = "F";
}
document.writeln("The final percent grade is "+sum+"%. Your grade letter is: "+grade+".");
</script>
</html>
Take the values from textboxes and give a button get Results and display the result in the output div.
Here is how I have done.
In javascript, take values from the textboxes using document.getElementById("<ID>").value and store it in a variable. Follow the same step for all the input boxes. And process the values obtained from textboxes and display it when the button is clicked.
Here is a simple code snippet which does the same thing using fields.
function myFunction()
{
var a1 = parseFloat(document.getElementById("a1").value);
var a2 = parseFloat(document.getElementById("a2").value);
var a3 = parseFloat(document.getElementById("a3").value);
var a4 = parseFloat(document.getElementById("a4").value);
var mid = parseFloat(document.getElementById("mid").value);
var fe = parseFloat(document.getElementById("fe").value);
var fp = parseFloat(document.getElementById("fp").value);
var sum=((a1+a2+a3+a4)/4)*(4*0.25)+(mid*0.25)+(fe*0.25)+(fp*0.25);
var grade;
if (sum >= 94.0) {
grade = "A";
} else if (sum <= 94.0 && sum >= 90.0) {
grade = "A-";
} else if (sum <= 90.0 && sum >= 87.0) {
grade = "B+";
} else if (sum <= 86.9 && sum >= 84.0) {
grade = "B";
} else if (sum <= 83.9 && sum >= 80.0) {
grade = "B-";
} else if (sum <= 79.9 && sum >= 77.0) {
grade = "C+";
} else if (sum <= 76.9 && sum >= 74.0) {
grade = "C";
} else if (sum <= 73.9 && sum >= 70.0) {
grade = "C-";
} else if (sum <= 69.9 && sum >= 67.0) {
grade = "D+";
} else if (sum <= 66.9 && sum >= 64.0) {
grade = "D";
} else if (sum <= 63.9 && sum >= 60.0) {
grade = "D-";
} else if (sum <= 60.0) {
grade = "F";
}
document.getElementById("result").innerHTML = ("The final percent grade is "+sum+"%. Your grade letter is: "+grade+".");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
a1: <input type="text" id="a1"><br><br>
a2: <input type="text" id="a2"><br><br>
a3: <input type="text" id="a3"><br><br>
a4: <input type="text" id="a4"><br><br>
mid: <input type="text" id="mid"><br><br>
finalexam: <input type="text" id="fe"><br><br>
finalproject: <input type="text" id="fp"><br><br>
<button onclick="myFunction()">Get Results</button><br><br>
<span id="result"></span>
</body>
</html>
Thank you.

Trying to find the average

I need to know why when I try to divide student 1,student 2 and student 3. I think it might be a looping error since the number that it give's me is numbering in the thousands but I don't see how that could be happening.
function averageOfThreeScores() {
var student1;
var student2;
var student3;
var end;
do {
student1 = prompt("What are the scorces of students 1?");
student2 = prompt("What are the scorces of students 2?");
student3 = prompt("What are the scorces of students 3?");
end = prompt("Would you like to end, type yes to end.");
var average = (student1 + student2 + student3) / 3;
if (average <= 59) {
document.write(average + " Your score is F <br/>");
} else if (average <= 69) {
document.write(average + " Your score is D <br/>");
} else if (average <= 79) {
document.write(average + " Your score is C <br/>");
} else if (average <= 95) {
document.write(average + "That's a great score <br/>");
} else if (average <= 100) {
document.write(average + "God like </br>");
} else {
document.write(average + " End <br/>");
}
}
while (end != "yes");
}
You expect the sum of student grades to be number but in fact they are concatenated as string. So if user types following values for example:
for student1: 13
for student2: 36
for student3: 50
The average will be 44550 because the sum will be (concatenated strings): 133650
To fix this, just convert the type to number when you get it.
student1 = parseInt(prompt("What are the scorces of students 1?"));
student2 = parseInt(prompt("What are the scorces of students 2?"));
student3 = parseInt(prompt("What are the scorces of students 3?"));

If statement does not repeat when condition is met?

I want the script to keep prompting the user for a valid input which is from 0 to 100 but can't get it to work. I am more confused than when I started to work on this script last night. This is my homework and the teacher has asked us to use if statement that is why I haven't tried to use the while loop but maybe I should.
Here is the code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade</title>
<script type="text/javascript">
var grade = Number(prompt("What did you score: ", "Your Score Here!"));
if (grade < 0 || grade > 100) {
grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
} else if (grade >= 0 && grade < 60) {
grade = "F";
} else if (grade >= 60 && grade < 70) {
grade = "D";
} else if (grade >= 70 && grade < 80) {
grade = "C";
} else if (grade >= 80 && grade < 90) {
grade = "B";
} else if (grade >= 90 && grade <= 100) {
grade = "A";
}
document.write("<strong>Your grade is:</strong> " + grade);
</script>
</head>
<body>
</body>
</html>
Yes you would use a while loop. In this case you would have a flag that checks if the input is invalid. We can assume it's valid in the loop, and when the invalid check goes through change it to being invalid (false), and cause the loop to repeat.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade</title>
<script type="text/javascript">
var grade = Number(prompt("What did you scrore: ", "Your Score Here!"));
var valid = false;
while(!valid)
{
valid = true; // assume it's valid
if (grade < 0 || grade > 100) {
grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
valid = false; // It it happens to not be valid, change it to invalid
} else if (grade >= 0 && grade < 60) {
grade = "F";
} else if (grade >= 60 && grade < 70) {
grade = "D";
} else if (grade >= 70 && grade < 80) {
grade = "C";
} else if (grade >= 80 && grade < 90) {
grade = "B";
} else if (grade >= 90 && grade <= 100) {
grade = "A";
}
}
document.write("<strong>Your grade is:</strong> " + grade);
</script>
</head>
<body>
</body>
</html>

Need a Java IF Statement for Grading System

I need someone to show me how to try add an IF statement after the user put's in their grade, the statement needs to display the alert right at the end if the mark is greater than 100 or less than 0. I've tried many different things and really not sure how to present this at all. If anyone could show me how to do it would be great.
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if( mark > 70 )
{
grade = "First Class";
}
else if( mark > 60 )
{
grade = "Upper Second";
}
else if( mark > 50 )
{
grade = "Lower Second";
}
else if( mark > 40 )
{
grade = "Third Class";
}
else if( mark < 40 )
{
grade = "Fail";
}
alert( "Mark: " + mark + "% - Grade: " + grade );
}
else
{
alert( "Invalid mark, outside range 0-100" );
}
You should check your value bounds before you begin grading like
if (mark < 0 || mark > 100)
{
alert('Invalid mark, outside range 0-100');
}
else if (mark > 70)
{
grade = 'First Class';
}
else if (mark > 60)
{
grade = 'Upper Second';
}
else if (mark > 50)
{
grade = 'Lower Second';
}
else if (mark > 40)
{
grade = 'Third Class';
}
else if (mark <= 40)
{
grade = 'Fail';
}
Also, notice that you either need mark >= 40 for third class or mark the user's grade as fail if mark <= 40. Otherwise, you'll miss grading when the score is 40.
At the end, you can simply check if the grade was initialized or not to show the grade alert.
if (grade != null)
{
alert('Mark: ' + mark + '% - Grade: ' + grade);
}
This seems to work:
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if (mark>100) grade="unclassified";
else if( mark > 70 ) grade = "First Class";
else if( mark > 60 ) grade = "Upper Second";
else if( mark > 50 ) grade = "Lower Second";
else if( mark > 40 ) grade = "Third Class"
else if( mark >= 0 ) grade = "Fail";
else grade="unclassified";
if (grade!="unclassified") alert( "Mark: " + mark + "% - Grade: " + grade );
else alert( "Invalid mark, outside range 0-100" );
It first checks for a mark over 100. All the elseif's will fail as soon as one of the if clause's makes it. It stored 'unclassified' as the grade. The grade of fail is given to any score 0 to 40 inclusive, if this fails, grade is defaulted to unclassified. We now break out of the loop and evaluate grade separately - if it is not 'unclassified' then the mark was valid, and we alert the grade, if 'grade' is equal to 'unclassified' then the alert says so with 'Invalid mark, outside range 0-100'.
One more thing, in JavaScript if there is only one line of code after a comparision, you do not need to use curly brackets {}, so instead of:
else if( mark > 60 ) {grade = "Upper Second";}
we can use:
else if( mark > 60 ) grade = "Upper Second";
(although this isn't true for functions which needs {} regardless of the number of lines in the function body.)
Your code is failing because you are not checking whether the mark is below (or equal to) 100 and above (or equal to) 0. This way if you get 110 you get first class while if you get -10 you get fail.
You just need to make sure that there the mark is smaller or equal to 100 in the first series of if, greater or equal to 0 in the last if, and then before alerting that the mark is once more between 0 and 100 (included) before you print what you want to print. Do it like this :
if( mark > 70 && mark <= 100)
{
grade = "First Class";
}
else if( mark > 60 && mark <= 100)
{
grade = "Upper Second";
}
else if( mark > 50 && mark <= 100)
{
grade = "Lower Second";
}
else if( mark > 40 && mark <= 100)
{
grade = "Third Class";
}
else if( mark < 40 && mark >= 0)
{
grade = "Fail";
}
if (mark <= 100 && mark >= 0) {
alert( "Mark: " + mark + "% - Grade: " + grade );
}
else
{
alert( "Invalid mark, outside range 0-100" );
}
OR You could also do (checking if the mark is between 0 and 100 only in the beginning):
if (mark >= 0 && mark <= 100) {
if( mark > 70)
{
grade = "First Class";
}
else if( mark > 60)
{
grade = "Upper Second";
}
else if( mark > 50)
{
grade = "Lower Second";
}
else if( mark > 40)
{
grade = "Third Class";
}
else if( mark < 40)
{
grade = "Fail";
}
}
else {
alert( "Invalid mark, outside range 0-100" );
}
if (mark <= 100 && mark >= 0) {
alert( "Mark: " + mark + "% - Grade: " + grade );
}
By the way this is not Java, if you want Java then replace alert with System.out.println ...

Categories

Resources