Introduction
In this article, I explain how to find the hypotenuse. A Hypotenuse of a number is the square root of the sum of two square numbers. For example, suppose there are two numbers say a and b. The addition of the squares of these numbers is a*a + b*b. Now the Hypotenuse of the number c is represented as:
c*c = a*a + b*b
So the value of c will be the square root of a*a + b*b number. To see how it works, use the following instructions:
Let's create a TypeScript app in Visual Studio and write our code.
Step 1. Open Visual Studio 2012 and click on "File" -> "New" -> "Project...". A window is shown. In that window select HTML application with TypeScript under the Visual C# template and then give the name of your application and then click OK.
Step 2. The TypeScript application contains a file, "app.ts", which is the TypeScript file, "app.js" which is the JavaScript file, "app.css" which is the StyleSheet and "default.html" which is the HTML file.
Step 3. Now open the app.ts TypeScript file and write the code as:
- class Point {
- x: number;
- y: number;
- constructor(x: number, y: number) {
- this.x = x;
- this.y = y;
- }
- hypotenuse() {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- }
- }
- var p = new Point(3,4);
- var dist = p.hypotenuse();
- alert("Hypotenuse of 3 and 4 is: " + dist);
In this file, I create a class name Point which takes two parameters x and y of number type, these two parameters are passed to the constructor, to be processed in the function. Now a function named Hypotenuse is declared which returns the Square root of the sum of these squares of numbers. All this work is done in the class. Now outside of the class an object of this class p is created in which I passed the two parameters values that are 3 and 4. Now the function of the object is called which returns the result and is displayed in the alert box.
Step 4. Open the app.js file and write the code as:
- var Point = (function () {
- function Point(x, y) {
- this.x = x;
- this.y = y;
- }
- Point.prototype.hypotenuse = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- };
- return Point;
- })();
- var p = new Point(3, 4);
- var dist = p.hypotenuse();
- alert("Hypotenuse of 3 and 4 is: " + dist);
Step 5. Open the default.htm file and write the code as:
- <!DOCTYPE html>
- <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta charset="utf-8" />
- <title>Hypotenuse Example</title>
- <link rel="stylesheet" href="app.css" type="text/css" />
- </head>
- <body>
- <h1>Finding Hypotenuse</h1>
- <div id="content">
- <script src="app.js">
- </script>
- </div>
- </body>
- </html>
Step 6. Now run the application. The output will look like:
Summary
In this article, I explained how to find the Hypotenuse using TypeScript.