JavaScript Course

Lesson 15 : Avoiding square roots of negative numbers.

This lesson is about choosing to do either one thing or another (simple selection) This is done using the if instruction. If you have not done so already you are advised to look at the relevant lecture: The if instruction.

When writing programs, you may sometimes have to get the square root of a number which is stored in a variable. You can not know, when you are writing a program, whether the number in the variable is negative or positive. If the number turns out to be negative, and you try to get the square root of the number, the program will stop because it is impossible to get the square root of negative number. When this situation occurs, you should use an if instruction to check whether the variable contains and negative number, and output an error message if it does. If it does not contain a negative number, your program should continue with the calculation it wishes to do.

Try out the following program a few times entering both positive numbers and negative numbers when asked!

num=promptNumber("Enter a number that is greater than or equal to zero!")

if (
num < 0)
{

alert("I can't get the squart root of a negative number")

}
else
{

root=Math.sqrt(num)
alert ("The square root of that number is: " + root)
}

Notice, by the way, how you calculate the square root of a number.


Assignment 15

Write a program that will ask for values for variable a and b and then attempt to calculate the square root of a - b , if it can. Otherwise, it should output an error message saying that it cannot do the calculation. In what situation do you think that this cannot be calculated? You can calculate the required square root as follows: Math.sqrt(a - b) , however remember you have to put the result of this calculation into a variable and then output it.

It may be worth reminding you at this stage that most people learn programming by reading other programs and making the appropriate changes for their own program. So, rather than starting your program from scratch, you should make the required changes to the program above to get it to carry out the task in this assignment.

Check that the program works, then make a note of the program .

End of Lesson :