我需要用户填写一个整数,但是使用下面显示的代码,也允许使用双精度数。如何将其更改为仅允许整数?
do{
$opgegevenGetal = read-host "Enter an integer"
if(![bool]($opgegevenGetal -as [int])){
write-host "Only integers please"
}
}
until ([bool]($opgegevenGetal -as [int]))
我需要用户填写一个整数,但是使用下面显示的代码,也允许使用双精度数。如何将其更改为仅允许整数?
do{
$opgegevenGetal = read-host "Enter an integer"
if(![bool]($opgegevenGetal -as [int])){
write-host "Only integers please"
}
}
until ([bool]($opgegevenGetal -as [int]))
尝试:
do{
$opgegevenGetal = read-host "Enter an integer"
$a = ""
if( ![int32]::TryParse( $opgegevenGetal , [ref]$a ))
{
write-host "Only integers please"
}
} until ($a -gt 0)
接受0
作为输入的代码:
do{
$opgegevenGetal = read-host "Enter an integer"
$a = ""
if( ![int32]::TryParse( $opgegevenGetal , [ref]$a ))
{
write-host "Only integers please"
}
} until ($a -gt 0 -or $opgegevenGetal -eq '0')
或者:
do{
$opgegevenGetal = read-host "Enter an integer"
$a = ""
$b = [int32]::TryParse( $opgegevenGetal , [ref]$a )
if( !$b)
{
write-host "Only integers please"
}
} until ($b)
克里斯蒂安回答的更紧凑的版本:
$value = 0
$read = Read-Host 'Enter an integer'
while( ![int]::TryParse( $read, [ref]$value ) ) {
$read = Read-Host 'Only integers please'
}