The PowerShell function allows you to find the square of a number:

This is my function to find the squared 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, not 16? Thanks.

+5
source share
3 answers

It seems that Read-Host returns the string, and the string - any value in powershell, leads to the repeated value of the string. You must force powershell to treat $value as an integer. Try the following:

 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" 
+5
source

In addition to Alistair's answer about the conversion, the string returned by Read-Host to int , you can use the Math library to round the value.

Code example

 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 value: 4
4 * 4 = 16

+5
source

This is similar to "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 
-1
source

All Articles