7

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.

3 Answers 3

6

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

0
5

It seems that Read-Host is returning a string, and a string times any value in powershell, results in string repeated value times. You need to make powershell treat $value as an integer. Try this:

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

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

It is like "4" * "4", and PowerShell converts the second "4" to int, so it returns "4444".

4 * 4 = 16
"4" * "4" = "4444"
"4" * 4 = "4444"
4 * "4" = 16
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.