請參閱下面的代碼##如果用戶輸入 0 或 a100 或非數值的 temp,我需要顯示“錯誤:您必須輸入數值!” Write-host $("Error: You must enter a numeric Value!") ## 然后回傳開始 ##im 猜測是否 ($value isnot [int]) 或類似的東西才能作業。謝謝。##Error 我沒有正確編碼......華氏溫度是多少:a111 ##Cannot 將值“a111”轉換為型別“System.Single”。錯誤:“輸入字串的格式不正確。”
Write-Host("="*31)
Write-Host $("Fahrenheit to Celsius Converter")
Write-Host $("Script Written By Jesse ")
Write-Host("="*31)
$value = (Read-Host("What is the temperature in Fahrenheit"))
$fahr = (($value -32) /9) *5
Write-Host $("Fahrenheit", $value, "is equal to Celsius:", [Math]::Round($fahr,3))
$input = (Read-Host("Do you want to convert another Fahrenheit value? (1 = yes, 0 = no)?"))
Write-Host ("="*31)
while ($input)
{
if ($input -eq 1)
{
Write-Host $("Fahrenheit to Celsius Converter")
Write-Host $("Script Written By Jesse Nieto ")
Write-Host ("="*31)
$value = (Read-Host("What is the temperature in Fahrenheit"))
$fahr = (($value -32) /9) *5
Write-Host $("Fahrenheit", $value ,"is equal to Celsius:" ,[Math]::Round($fahr,3))
$input = (Read-Host("Do you want to convert another Fahrenheit value? (1 = yes, 0 = no)?"))
Write-Host("="*31)
}
elseif ($input -eq 0)
{
Write-Host $("Thank You. Bye! ")
break
}
else
{
Write-Host $("Please enter a valid option! ")
$input = (Read-Host ("Do you want to convert another Fahrenheit value? (1 = yes, 0 = no)?"))
Write-Host ("="*31)
}
}
uj5u.com熱心網友回復:
你的腳本中有很多冗余代碼可以簡化,最大的問題是使用$input它是一個自動變數,不應該手動分配。至于從華氏溫度轉換為攝氏溫度的公式,你可以使用一個函式,除此之外,根據谷歌的說法,這個公式應該是(X ? 32) × 5 / 9雖然我不是這方面的專家,但你可以隨意改變。
function ConvertTo-Celsius {
param([int]$Value)
($value - 32) * 5 / 9
}
:outer while($true) {
$value = Read-Host "What is the temperature in Fahrenheit"
try {
$celsius = ConvertTo-Celsius $value
}
catch {
# If input was invalid restart the loop
Write-Host "Invalid input, only integers allowed!"
continue
}
Write-Host "Fahrenheit $value°F is equal to $([math]::Round($celsius, 3))°C"
do {
$shouldExit = Read-Host "Do you want to convert another Fahrenheit value? (1 = yes, 0 = no)?"
switch($shouldExit) {
0 {
Write-Host "Thank You. Bye!"
break outer
}
1 { continue }
Default { Write-Host "Please enter a valid option!" }
}
} until($shouldExit -eq 1)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437110.html
上一篇:如何使collat??z的輸出看起來像一個串列并帶有標簽?
下一篇:IFTRUE那么變數名
