December 21, 2024
Answer to JavaScript Exercise Q2
//declare variables
var num, cube;
/* declare and initialise some more variables
and assign the input from two dialogue boxes
*/
var numStr = window.prompt('Enter a number', '');
//convert string variable to number
num = parseFloat(numStr);
// form the cube
cube = num * num * num;
//output a suitable message
document.write('The cube of ' + num + ' is:' + '<BR>');
//convert the cube to a string and output the value
document.write(cube);
//note that you can also write
//document.write(cube.toString());
Notes:
- All input made via a dialogue prompt box will be in the form of a string. Consequently one needs to be very careful when numbers are being manipulated, in which case explicit conversion will be required by using the parseFloat() function.
- When passing a value for output, via the browser or an alert box, JavaScript
will automatically attempt to convert this value to a string. I have written
document.write(cube);
even though cube is a number data type the interpreter will use auto conversion to construct a string. The final alternative
document.write(cube.toString());
is in fact not needed because this is what JavaScript does when it applies auto conversion. The number, referenced by cube, is converted to a String object, which is then operated on by the toString() method.
Back « JavaScript numbers
⇑ Up to top of page