0

Was just wondering on how to add arrays, i can * it, subtract it but cant't add. Heres the code.

distance[i] = window.prompt("Please enter distance in miles");
total = distance[0] + distance[1] + distance[2] + distance[3] + distance[4]
average = total / 5
miles.push(distance);distance[i] = window.prompt("Please enter distance in miles");
total = distance[0] + distance[1] + distance[2] + distance[3] + distance[4]
average = total / 5
miles.push(distance);






console.log(miles);
document.write("calculation for "+name + "<br />Fuel consumption: " + fuel + "<br />Average distance travelled:" + average +'');}
2
Contributors
6
Replies
14
Views
3 Years
Discussion Span
Last Post by JorgeM
1

You have to be patient. this isnt live help, at least not usually.

Your code isnt complete, but most likely what you are seeing is that when you try to add the data store in the arrays, the information is being treated as a string, instead a number.

The simple answer is use hte Number(). However, it would be more appropriate if you parse your input, do some validation before you assume that the input is an actual number.

Edited by JorgeM

0

Sorry for the lack of patience, basically this program asks the user 5 times to enter a number, stores it in the array. i'm new to javascript so i wouldn't know where to put the parseint, it would be extremely helpful if you can have a play around with it.

0

Hey man, thanks for your help!! i used the number function to make it work.

Thanks again

p.s(thanks)

0

You could do something simple like...

 var a = parseInt(window.prompt("Please enter distance in miles"));

Do it five times, or do something more sophisticated like use a loop to collect input. After you collect the input use a conditional statement to verify if you were able to extract an integer or not. Then take some action like ask again, continue or exit.

If you are not familiar with javascript, create a basic program without shiny bells, no arrays, loops, validation, etc... Get that working, then try to make the program more efficient by adding in the loops and continue until you understand the code and it's working according to the requirements.

0

Glad you figured it out.

Don't be so impatient to have someone do the work for you. Try, ask for help, try again, repeat. You will find that you will be your best teacher. Good luck.

Edited by JorgeM

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.