Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell function to find the square of a number:

This is my function for finding the square of a value:

function Get-Square($value)
{
    $result = $value * $value
    return $result
}

$value = Read-Host 'Enter a value'
$result = Get-Square $value
Write-Output "$value * $value = $result"
PS C:\Users> .\Get-Time.ps1
Enter a value: 4
4 * 4 = 4444

Why is the result 4444 and not 16? Thank you.

like image 702
gordon sung Avatar asked Jun 01 '16 03:06

gordon sung


Video Answer


1 Answers

In addition to the Alistair's answer about converting, the string returned by Read-Host to int, you might want to use the Math library to square the value.

Sample Code

function Get-Square([int] $value)
{
    $result = [Math]::Pow($value,2)
    return $result
}

$value = Read-Host 'Enter a value'
$result = Get-Square $value
Write-Output "$value * $value = $result"

Results

Enter a value: 4
4 * 4 = 16

like image 82
TravisEz13 Avatar answered Nov 15 '22 07:11

TravisEz13