Enzo Nassif
Enzo Nassif

Reputation: 13

Issues with arithmetic-operators

my problem is that I'm trying to put a simple math formula in a PowerShell script but this "arithmetic-operators" is an issue now for me, It was used to work this way, but something changed and now doesn't matter what I put in it multiples for more numbers as if they were letters, (it's only stacking all of them together)

I even tried fixing it using

$x=[int]$xx

to fix my variables so PowerShell could understand, and it did work just not with broken numbers Ex: 7.5 or 3.1 or 9.6 No broken numbers. Can anyone help me

$pi=[math]::pi
$xx= Read-Host -prompt "X "
$yy= Read-Host -prompt "Y "
$zz= Read-Host -prompt "Z "
$x=[int]$xx
$y=[int]$yy
$z=[int]$zz
$re = $z * $y
$r = $z * $x + $y * $x + $z * $x + $y * $x
$res = 2 * ($re) + $r
echo .
echo "$r = $z * $x + $y * $x + $z * $x + $y * $x"
echo .
echo "$re = $z * $y"
echo .
echo "$res = 2 * ($re) + $r"
echo .
echo "Total = $res"
echo .
pause

if you run this and put X as 27, Y as 7.5 and Z as 17, your answer should be 1578, and you fixed it

Upvotes: 1

Views: 279

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You are getting the wrong answer because 7.5 is not an [int]. It is rounding 7.5 to 8 to cast it to an int. You need $y=[single]$yy to make this work or any other type that supports decimals. I would replace all [int] with [single] if expect decimal values. See the following:

$pi=[math]::pi
$xx= Read-Host -prompt "X "
$yy= Read-Host -prompt "Y "
$zz= Read-Host -prompt "Z "
$x=[single]$xx
$y=[single]$yy
$z=[single]$zz
$re = $z * $y
$r = $z * $x + $y * $x + $z * $x + $y * $x
$res = 2 * ($re) + $r
echo "$r = $z * $x + $y * $x + $z * $x + $y * $x"
echo "$re = $z * $y"
echo "$res = 2 * ($re) + $r"
echo "Total = $res"

Output of the variables above:

$x,$y,$z,$re,$r,$res
27
7.5
17
127.5
1323
1578

Other types that you could potentially use are [double], which is the default type of uncasted numbers with decimals, and [decimal]. You can also use the -as type operator like $y = $yy -as [double]. See About Type Operators

Upvotes: 4

Related Questions