Correcting my Javascript math program?
|
04-08-2014, 04:17 AM
Post: #1
|
|||
|
|||
Correcting my Javascript math program?
Below is my Javascript math program. I'm not sure what I am doing wrong but it will not function properly. Please help!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>JavaScript Functions</title> <script type="text/javascript"> var num1 = 0;//acts as a place holder for the user number var num2 = 0;//acts as a place holder for the user's second number var calculatedNum = 0;//place holder for the user's answer function calculation() { // type your calculation and output statements here calculatedNum = num1 * num2;//equation for the user's two numbers//holds user's first number and second number, then multiplies them together num1 = prompt("Please type the first number");//prompt asking for the user's first number num2 = prompt("Please type the second number");//prompt asking for the user's second number alert( num1 + " x " + num2 + " is " + calculatedNum + " ! " ); } // end calculation function </script> </head> <body> <h1></h1> </body> </html> Ads |
|||
04-08-2014, 04:25 AM
Post: #2
|
|||
|
|||
Try wrapping the num's in a parseInt()
Or parseFloat. Check the users input if it contains only number. Turn ',' into '.' Next times, tell what the output is or what happens when it goes wrong. Like, where you getting only "NaN"? //Not a number Or did you get "null" //user hit cancel Ads |
|||
04-08-2014, 04:30 AM
Post: #3
|
|||
|
|||
The order that things is a bit mixed up. Prompt the user. Then do the calculation. Finally, show the result.
- Dominic |
|||
04-08-2014, 04:38 AM
Post: #4
|
|||
|
|||
javascript reads from top to bottom. your variables were out of order. I fixed this. I also added a button so you can test that the function works, and the button can be easily removed if desired.
<html> <head> <title>JavaScript Functions</title> <script type="text/javascript"> var num1 = 0;//acts as a place holder for the user number var num2 = 0;//acts as a place holder for the user's second number var calculatedNum = 0;//place holder for the user's answer function calculation() { // type your calculation and output statements here num1 = prompt("Please type the first number");//prompt asking for the user's first number num2 = prompt("Please type the second number");//prompt asking for the user's second number calculatedNum = num1 * num2;//equation for the user's two numbers//holds user's first number and second number, then multiplies them together alert( num1 + " x " + num2 + " is " + calculatedNum + " ! " ); } // end calculation function </script> </head> <body> <button onClick="calculation()">test it.</button><!--DELETE THIS ENTIRE LINE TO ENTIRELY REMOVE THE BUTTON--> <h1></h1> </body> </html> |
|||
« Next Oldest | Next Newest »
|
User(s) browsing this thread: 1 Guest(s)