You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pythagore函数集成到PowerShell自定义菜单的选项1中

实现方法

1. 先修正pythagore函数的作用域问题

你之前把读取边长的代码写在了函数外面,属于全局变量,调用时容易出现取值异常,把读取逻辑移入函数内部即可,修改后代码如下:

Function pythagore {
    $length1 = Read-Host "enter first length"
    $length2 = Read-Host "enter second length"
    if ($Length1 -lt 1) { $Length1 = 1 } 
    if ($Length2 -lt 1) { $Length2 = 1 }
    $length3 = ([math]::Sqrt(([math]::Pow($Length1, 2)) + (([math]::Pow($Length2, 2)))))
    Write-Host "The missing length is $length3"
    # 增加暂停逻辑,看完结果按任意键返回菜单
    Read-Host "Press any key to go back to menu"
}

2. 修改Show-Menu函数的选项1分支

找到Show-Menu函数里switch判断的'1'对应代码块,把原有的提示文本替换为调用pythagore函数的语句即可,修改后switch部分代码如下:

switch ($selection)
{
    '1' {
        # 选中选项1时直接调用勾股计算函数
        pythagore
    } '2' {
        'You chose option #2'
    } '3' {
        'You chose option #3'
    } '4' {
        'You chose option #4'
        
    }  '5' {'You chose option #5'
    }  'q' { return
       
    }
}

可选优化:增加菜单循环

如果需要选完功能后自动返回菜单而不是直接退出,可以给整个菜单逻辑套上do-while循环:

function Show-Menu
{
    param (
        [string]$Title = 'back to school'
    )
    do {
        Clear-Host
        Write-Host "================ $Title ================"
        
        Write-Host "1: Press '1' to calculate the missing length of a triangle."
        Write-Host "2: Press '2' to Calculate the area of a circle with a given diameter ."
        Write-Host "3: Press '3' to Calculate the volume of a cylinder from a given diameter and height. ."
        Write-Host "4: Press '4' to Calculate the volume of a sphere with a given diameter ."
        write-host "5: Press '5' to Calculate the factorial of an integer ."
        write-host "Q: Press 'Q' to exit"
        $selection = Read-Host "Please make a selection"
        switch ($selection)
        {
            '1' {
                pythagore
            } '2' {
                'You chose option #2'
            } '3' {
                'You chose option #3'
            } '4' {
                'You chose option #4'
                
            }  '5' {'You chose option #5'
            }  'q' { 
                return
            }
        }
    } while ($true)
}

内容的提问来源于stack exchange,提问作者Dali Lemkecher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:27:05