Trying to find the average - javascript

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?"));

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);
}

How to calculate average grade

I'm new to JavaScript and can't seem to figure out why my last function is not doing what it's suppose to do which is to use the average of entered grades(number) from the user to return a letter grade.
My first function is working how it should and my second function is written correctly (I think) but for my third function i'm not sure what i'm doing wrong because when I test run nothing shows up.
Here is what I've done within my code:
var grades = [];
var totalSum = 0;
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
var average = totalSum / grades.length;
}
}
function letterGrade() {
if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
You need average variable as global and some fix in your letterGrade() like this :
add: letterGrade() will always return A if score is 90 or below
var grades = [];
var totalSum = 0;
var average = 0
// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {
if (average >= 90 && average <= 100) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average >= 80 && average <= 89) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average >= 70 && average <= 79) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average >= 60 && average <= 69) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else if (average <= 59) {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>
It is a scope problem. You need to define the variable average at the top and not inside the function gradeAverage.
var grades = [];
var totalSum = 0;
var average = 0; /* Added */
// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {
if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>
3 issues here:
In the 3rd function you use 'average' event though its not defined globally - meaning its not available in the function.
It seems you check totalSum <= x even though you probably want to check average <= x.
The order of checks in the 3rd function will always result in the first check. Because even if average <= 60 its also <= 90. Reverse the order of checks so the lower grades will be first:
if (totalSum <= 50) {
document.getElementById("finalGrade").innerHTML += average + " F";
} else if(totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else {
document.getElementById("finalGrade").innerHTML += average + " A+";
}
move the average var declaration outside the function (not really recommended, see later)
reverse the ifs from <= to >=
use average and not total sum in the ifs
var grades = [];
var totalSum = 0;
var average =0;
// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {
if (average>= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average>= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average>= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average>= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>
Better, pass the var:
// function to read five values from series of prompts stored in array
function getGrades() {
var grades = [];
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
return grades;
}
// function to calculate the average of the five entered grades and store it in a variable
function getSum(grades) {
var totalSum = 0;
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
}
return totalSum;
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade(grades) {
var totalSum = getSum(grades);
var average = totalSum / grades.length;
var finalGrade = "";
if (average >= 90) {
finalGrade = "A";
} else if (average >= 80) {
finalGrade = "B";
} else if (average >= 70) {
finalGrade = "C";
} else if (average >= 60) {
finalGrade = "D";
} else {
finalGrade = "F";
}
document.getElementById("finalGrade").innerHTML += average + " " + finalGrade;
}
var grades = getGrades()
letterGrade(grades);
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>
Before giving the solution you need to understand the scopes of variables in javascript.
Consider the following code:
function myFunction() {
var carName = "Volvo";
//code here CAN use the variable carName
}
function someAnotherFunction(){
console.log(carName);
//code here CANNOT use the variable carName
//It will the error that carName is not defined.
}
//code here CANNOT use the variable carName
Another case:
var carName = "Volvo";
function myFunction() {
console.log(carName);
//code here CAN use the variable carName
}
function someAnotherFunction(){
console.log(carName);
//code here CAN use the variable carName
}
console.log('Check my value here again: '+carName);
//code here CAN also use the variable carName
The difference to note here is, The scope/visibility of variable is limited to opening and closing brackets in which it is placed. Outside the closing brackets the very same variable won't be visible outside the brackets, in which it was declared.
Same way you cannot use average variable outside the brackets from where it was declared.
Looking at your code few things needs to be changed.
Move the average declaration outside the brackets, so that it becomes visible.
var average =0;
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
And in the function where grades are calculated, the condition when the average is greater than 90 needs to be added.
function letterGrade() {
if (average >= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average >= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average >= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average >= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
Rest would be fine as it is.
Hope this helps.

averaging numbers and display grouped average

I am trying to write a code that prompts the user to add 4 numbers and average them out and depending if that answer is 100+, 75-100, 50-75, 50- it checks if its in between the specified number zones and shows the answer respectively in a prompt box.
edit The code doesn't give anything lower than group 75-100 regardless. for example, if I enter four 20's it says that its between 75 and 100 (a+ grade) which makes no sense to me. If anyone has a idea please help.
<!DOCTYPE html>
<html>
<head>
<title> Looping assignment
</title>
</head>
<script>
var grades = new Array()
for (i = 0; i < 4; i++) {
grades[i] = parseFloat(prompt("Enter your grades:"))
}
var total = (grades[0] + grades[1] + grades[2] + grades[3])
var average = (total / 4)
if ( average >= 100)
alert("How is the average higher than 100! A+ grade/n " + average);
if ( average > 75 && average <99)
alert("The average is between 75 and 100. B grade /n " + average);
if ( average > 50 && average <75)
alert("The average is between 75 and 50. C grade /n " + average);
</script>
</body>
</html>
You need to use && operator instead of ;
var grades = new Array()
for (i = 0; i < 4; i++) {
grades[i] = parseFloat(prompt("Enter your grades:"));
}
var total = (grades[0] + grades[1] + grades[2] + grades[3])
var average = (total / 4)
if (average >= 100)
alert("How is the average higher than 100! A+ grade/n " + average);
if (average > 75 && average <=99)
alert("The average is between 75 and 100. B grade /n " + average);
if (average > 50 && average <=75)
alert("The average is between 75 and 50. C grade /n " + average);

Using JS i need to create a Average variable

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"
}

Find the sum of a Javascript array and divide by its length

I'm almost embarrassed to ask this.
I'm a beginner programmer, and Javascript is very confusing to me. I managed to put together this much with the help of my instructor, but there are some simple things I can't get right.
I tried search Stack Overflow for a thread that would answer my question, but all of them I've seen contain code that I haven't learned about yet, so they're all just gibberish to me.
What I'm trying to do is add all the values of an Array and divide the sum by the array's length, ergo, find the average. The description of the assignment is find the average of any number of students' grades.
My two problems are
I can't figure out how to get the sum of all numeric values in the Array and,
For some reason, array.length returns one more than the actual length of the Array, even if I add a -1. (ex. if I enter 6 values, the array.length would return 7.)
I know where the problem is but I can't figure out what I need to enter. This assignment is due tomorrow, so anyone's time and effort is appreciated.
Here is my script:
<script type="text/javascript">
var allGrades = new Array();
var g = 0;
var l = 0;
var s = 0;
var t = 0;
do {
allGrades[g] = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "")
g++;
}
while (allGrades[g - 1] != "x")
for (l = 0; l < allGrades.length - 1; l++) {
s += allGrades[l] // Where I think the problem is
}
t == s / g - 1;
g == allGrades.length - 1; //
window.alert(g)
switch (t) {
case (t >= 90):
window.alert("Your average grade is " + (t) + ". " + "This is an A.")
break;
case (t >= 80 && t < 90):
window.alert("Your average grade is " + (t) + ". " + "This is a B.")
break;
case (t >= 70 && t < 80):
window.alert("Your average grade is " + (t) + ". " + "This is a C.")
break;
case (t >= 60 && t < 70):
window.alert("Your average grade is " + (t) + ". " + "This is a D.")
break;
case (t <= 60):
window.alert("Your average grade is " + (t) + ". " + "This is a failing grade.")
break;
}
</script>
I'm sorry if what I'm asking seems dumb. I've only been taking web programming for about two months, so I could really use some help!
Kyle
== is the comparison operator. You need to use the assignment operator (=) here:
t==s/g-1;
And the lines near it.
Also, for your own sake, do not use single-letter variable names unless you have a good reason for doing so.
Here's a cleaner way of writing the script:
var grades = [];
do {
var input = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "");
grades.push(parseFloat(input));
} while (input != 'x');
var sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[l];
}
var average = (sum / grades.length) * 100;
var grade;
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else {
grade = 'failing grade';
}
alert('Your average grade is ' + average + '. ' + 'This is a ' + grade);
t==s/g-1;
g==allGrades.length-1; //
Are both Comparisons, for assignment they should be
t=s/g-1;
g=allGrades.length-1;

Categories

Resources