I am having trouble calculating the mpgTotal. This should add together all of the mpgTankful and divide them by how many are added together (essentially finding the average of mpgTankful). I tried implementing a counter but It's not turning out how I'd like it to. It should keep counting until a user enters -1 to quit.
A sample result would be:
Miles user entered:
Gallons user entered:
mpgTankful:
mpgTotal: (in this case mpgTankful would be divided by 1)
Miles user entered:
Gallons user entered:
mpgTankful:
mpgTotal: (in this case add previous mpgTankful with current mpgTankful and divide by 2)
Miles user entered:
Gallons user entered:
mpgTankful:
mpgTotal: (in this case add first mpgTankful with second and current (third) mpgTankful and divide by 3)
var miles, //Miles driven
gallons, //Gallons used
mpgTankful, //MPG this tankful
mpgTotal, //Total MPG
mi, //Miles driven converted to integer
gal, //Gallons used converted to integer
count=0,
avg;
//Enter -1 to quit
while(miles!="-1"){
//Read in the Miles Driven from user as a String
miles=window.prompt("Enter miles (-1 to quit):");
if(miles=="-1"){
break;
}
//Read in the Gallons used from user as a String
gallons=window.prompt("Enter gallons:");
//Convert numbers from Strings to Integers
mi=parseInt(miles);
gal=parseInt(gallons);
//Calculate the MPG Tankful
mpgTankful=mi/gal;
//Calculate the Total MPG
mpgTotal+=mpgTankful;
count++;
if(count!=0){
avg=mpgTotal/count;
}
else
avg=0;
document.writeln("avg: " + avg);
//Print Results
document.writeln("<br/><br/>Miles driven: " + mi +
"<br/>Gallons used: " + gal +
"<br/>MPG this tankful: " + mpgTankful +
"<br/>Total MPG: " + mpgTotal);
}
You were almost there...
mpgTotal+=mpgTankful; can't work: the first time this is called, mpgTotal === undefined
The if(count!=0) is useless.. you incremented count one line above...
You calculated avg but didn't output it (according to the description for 'Total MPG: '): <br/>Total MPG: " + mpgTotal
For this example I added a looping check for invalid input (explanations in comments).
<script>
var miles=0 //Miles driven
, gallons=0 //Gallons used
, mpgTankful=0 //MPG this tankful
, mpgTotal=0 //Total MPG
, mi=0 //Miles driven converted to integer
, gal=0 //Gallons used converted to integer
, count=0
, avg=0
; // end vars
main: while(true){ //main loop, labeled 'main'
if( (miles=prompt('Enter miles ("-1" to quit):')) === '-1' )
break main; //well.. plain english..
if( isNaN(mi=parseInt(miles, 10)) ){ //check if we get a number
alert('Please enter a number or enter "-1" to quit.');
continue main;
}
while(true){
if( (gallons=prompt('Enter gallons ("-1" to quit):')) === '-1' )
break main; //NOT this inner loop.
if( isNaN(gal=parseInt(gallons, 10)) ){ //check if we got a number
alert('Please enter a number or enter "-1" to quit.');
//no need to instruct a continue for this loop..
} else break; //this inner loop (so we can go on with 'main' below).
}
mpgTankful=mi/gal; //Calculate the MPG Tankful
mpgTotal+=mpgTankful; //Calculate the Total MPG
avg=mpgTotal/++count; //Calculate avg (and pre-increment count)
//Print Results
document.writeln( '<br/><br/>Miles driven: ' + mi
+ '<br/>Gallons used: ' + gal
+ '<br/>MPG this tankful: ' + mpgTankful
+ '<br/>Total MPG: ' + avg
);
}
document.close(); //don't forget to close the body..
</script>
This should get you started.
Related
I'm taking a class on computer programming, and I have an assignment where I have to make a loop in which users enter data into a prompt, and at the end I will output the lowest, highest, average, and total of that data. The problem is, I can't figure out how to have that data stored as different values every time. Btw I'm using javascript, and the project has to be done with that language.
var g = 1;
var points = alert("Please enter the scores of the player in the prompts.");
var totalPoints = 0;
do {
var pointsCount = Number(prompt("Please enter how many points the user entered in Game " + g + ":"))
i++
g++
totalPoints += pointsCount
} while (pointsCount != -1)
alert("*** Your Player Stats *** /n" + " Minimum points: " + Math.min(pointsCount) + " Maximum points: " + Math.max(pointsCount) + " Average points: " + totalPoints/i + " Total points: " + totalPoints);*```
I would store data outside the loop and update it when needed. You don't have i varaible in your code. You can use here a while loop with true condition so it repeats infinitely, and break out of it using some condition (e.g. -1 as input). Take a look at the code below.
let totalPoints = 0;
let minPoints;
let maxPoints;
let numberOfGames = 0;
while(true){
let points = Number(prompt("Please enter how many points for this game"))
// skip invalid data
if(isNaN(points)){
continue;
}
// loop exit condition
if(points === -1) break;
// set min if not undefined or lower than recorded
if(!minPoints || points < minPoints){
minPoints = points;
}
// same as above but for max
if(!maxPoints || points > maxPoints){
maxPoints = points;
}
totalPoints += points;
numberOfGames++;
}
alert("*** Your Player Stats ***" + "\nMinimum points: " + minPoints + "\nMaximum points: " + maxPoints + "\nAverage points: " + totalPoints/numberOfGames + "\nTotal points: " + totalPoints);
I'd like to create an average calculator for test scores. Have the user enter numbers. They can enter as many as they want. Once they enter “-1”, end the program. Display the lowest test score, the highest test score, the sum of all test scores, and the average of all test scores.
The following is my code. I've already figured out how to do the sum of the scores. However, I don't know how I can turn ALL my inputs into a string - possibly output the lowest (Math.min), highest (Math.max) and average of the test score.
I tried joining strings together but in the end I couldn't figure out how to work!
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
var item = itemGrade + ", "
total += itemGrade;
if (itemGrade == -1) {
break;
}
}
document.write("Total: " + total)
Here is a short piece of code that should do the job. The syntax ${variable} with ` allows variables to become strings. Total score is how you've written it. Lowest and highest simply checks if the new score entered is a higher or lower number and replaces the variable as the new lowest/highest. A count is added to calculate the average of all scores.
var total_score = 0.0;
var average_score = 0.0;
var lowest_score = Infinity;
var highest_score = 0.0;
var count = 0.0;
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
if (itemGrade == -1) {
break;
}
total_score += itemGrade;
if (lowest_score > itemGrade){
lowest_score = itemGrade;
}
if (highest_score < itemGrade){
highest_score = itemGrade;
}
count++;
}
average_score = total_score/count;
document.write("Total Score: " + `${total_score}`);
document.write("Average Score: " + `${average_score}`);
document.write("Lowest Score: " + `${lowest_score}`);
document.write("Highest Score: " + `${highest_score}`);
var item = []
item.push(itemGrade)
You can create an empty array and use push() inside the while loop to add value to end of an array or use unshift() in case you want to add in starting position of the array
For some reason I'm having difficulty getting this while loop to work. It keeps crashing my browser whenever I try to test it out, and in the one case that I was able to see the results of the loop in the console, all I saw was NaN printed several times. Is there something I've forgotten in my code?
<div id="output"></div>
<script>
var starting = prompt("What is your starting balance?");
var target = prompt("What is your target balance?");
var interest = prompt("What is your interest rate?");
var periods = 0;
var current = starting;
var greaterThan = false;
while (greaterThan === false) {
if (current < target) {
current = current + (current * interest);
periods++;
} else {
greaterThan = true;
alert("it took " + periods + " periods to make your starting balance greater than your target balance.");
document.querySelector('#output').textContent = "to grow an initial investment of " + starting + " to " + target + " at a " + interest + " interest rate will require " + periods + " investment periods.";
}
}
</script>
The one problem I could see is, all your input values are string, not numbers so they are doing string comparison not numeric
var starting = +prompt("What is your starting balance?") ||0;
var target = +prompt("What is your target balance?")||0;
var interest = +prompt("What is your interest rate?")||1;
The + in front of prompt() is the unary plus operator
You are forgetting to convert the result from prompt from a string into a number.
var starting = parseFloat(prompt("What is your starting balance?"));
Do the same thing to the other numbers that are input by the user from the prompt.
First you need to convert your input into an integer value. The input from the prompt is a string. even if you enter 1 or 10 or any number. You can use parseInt() for that. and because you are asking for interest rate, i think any user would enter something like 2. 5, or 10 as a percentile. not 0.1, or 0.05. Even if he does, the parseInt() function can't get it right because 0.05 is not an integer value. You can use parseFloat for that. so i suggest you look at my implementation of your code below. also, i have omitted the if else statements because they weren't necessary and would only make the code more complex.
<div id="output"></div>
<script type="text/javascript">
var starting = parseInt(prompt("What is your starting balance?"));
var target = parseInt(prompt("What is your target balance?"));
var interest = parseInt(prompt("What is your interest rate?"));
var periods = 0;
var intrate = interest/100;
var current = starting;
while (current< target) {
current += (current*intrate);
periods += 1;
}
alert("it took " + periods + " periods to make your starting balance greater than your target balance.");
document.querySelector('#output').textContent = "to grow an initial investment of " + starting + " to " + target + " at a " + interest + " interest rate will require " + periods + " investment periods.";
</script>
I'm learning programming starting with Javascript, and my instructor had us doing a random dice roll, a simple Math.ceil(6*Math.random())
I was trying to slightly gameify it and judge the result. So, if you roll a 7, you win, any other roll you lose. The ultimate result would be,
"You rolled a: 7
You win!"
However, I attempt to accomplish by saying approximately:
console.log("You rolled a: " + diceSum);
if (dicesum() == 7) {
console.log("You win!");
} else {
console.log("Aw... you lose. Better luck next time");
}
diceSum() function evaluates each time, so I may get "You rolled a: 7" and "Aw... you lose" because the first roll was a 7, but by the time the if statement came in, the diceSum was something different.
How do I generate a random number like a dice roll and then reuse its value over and over?
Here's my current code (there is far more than necessary because I'm trying to display the values so I know if it is returning the correct answer):
//Functions
//Generate a random single roll of a dice
var getDieRoll = function() {
return Math.ceil(6*Math.random());
};
//Sum up two dice rolls
var diceSum = function() {
var firstDie = getDieRoll();
var secondDie = getDieRoll();
return firstDie+secondDie;
};
//
//Variables
//Check to see if total sum of the roll is 7
var winMsg = "Winner!"
var loseMsg = "Aw... you lose. Better luck next time."
//
//Outputs
//show total sum to compare with message below
console.log(diceSum())
//Return a message stating the result
console.log("You rolled a " + diceSum())
//View true false status to compare with message returned below
console.log(diceSum()==7)
//If diceSum is a 7, give winning message, otherwise give losing message
if (diceSum()==7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
You put the result in a variable, and use the variable:
var sum = diceSum();
//Outputs
//show total sum to compare with message below
console.log(sum);
//Return a message stating the result
console.log("You rolled a " + sum)
//View true false status to compare with message returned below
console.log(sum == 7);
//If diceSum is a 7, give winning message, otherwise give losing message
if (sum == 7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
By the way, the way to calculate the random number is wrong. The random method is defined to return a value that is 0 <= n < 1, i.e. it can be zero, but it can never be one.
If you use Math.ceil, the effect is that the result will occasionally be zero, and the chance to get a six is slightly smaller than the other numbers.
Use Math.floor instead:
function getDieRoll() {
return Math.floor(6 * Math.random()) + 1;
};
Save it to a variable:
var sum = diceSum();
console.log("You rolled a " + sum);
if (sum == 7) {
console.log(winMsg);
} else {
console.log(loseMsg);
}
Or:
var sum = diceSum(),
msg = sum == 7 ? winMsg : loseMsg;
console.log("You rolled a " + sum);
console.log(msg);
I'm trying to make a program that determines if a grade entered is passing or failing. It stops when the user enters -1. Once the user does enter -1, it has to print out the average of the passing scores and the total amount of scores. It's not really working correctly though. What am I doing wrong?
var countTotal=0; //variable to store total grades.
var countPassing=0; //variable to store total passing scores.
var x= 0; //variable to contain sum of all passing scores.
var grade=parseInt(prompt("Please enter a grade."));
while (grade != (-1*1))
{
if (grade > 65) {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is failing.<br>");
}
countTotal++;
}
//Loop ends
document.write("Total # of grades: " + countTotal); //Prints out total # of passing scores.
document.write("Passing average: " + ((x)/(countPassing))); //Prints out average of all passing scores.
Try working through it by hand. The user enters the very first grade. Then the loop starts. Immediately, you ask for a new grade, discarding the first one. If you move the prompt down to the end of the loop, it should work. Like this:
while (grade != (-1*1))
{
if (grade > 65) {
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
document.write(grade + " is failing.<br>");
}
grade=parseInt(prompt("Please enter a grade."));
countTotal++;
}