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

Bash脚本数字序列增减判断失效问题求助

问题解决:判断数字序列的递增/递减性

原脚本的核心问题

你的脚本仅实现了总和与平均值计算,完全缺失序列递增/递减的判断逻辑:

  • cresc和decresc变量始终为初始值0,从未根据数字变化更新状态,导致最后的if判断永远只会输出"SEQ. CRESCENTE"
  • 未处理输入数字不足2个的边界情况(此时无法判断序列趋势)
  • 输出格式和你的预期不符

修改后的完整脚本

#!/bin/bash

# 检查输入参数数量,至少需要2个数字才能判断趋势
if [ $# -lt 2 ]; then
    echo "错误:请输入至少2个数字"
    exit 1
fi

# 初始化变量
tot=0
numeri=0
is_increasing=1  # 1代表假设是递增,0代表不是
is_decreasing=1  # 1代表假设是递减,0代表不是

# 保存第一个数字作为前一个数字
prev_num=$1

# 遍历所有数字,计算总和并判断趋势
for number in "$@"
do
    # 计算总和与数字个数
    tot=$((tot + number))
    numeri=$((numeri + 1))

    # 跳过第一个数字,从第二个开始比较
    if [ "$number" != "$prev_num" ]; then
        if [ "$number" -gt "$prev_num" ]; then
            # 当前数字大于前一个,标记不是递减序列
            is_decreasing=0
        elif [ "$number" -lt "$prev_num" ]; then
            # 当前数字小于前一个,标记不是递增序列
            is_increasing=0
        fi
        # 更新前一个数字为当前数字
        prev_num=$number
    fi
done

# 输出总和与平均值
echo "TOTALE = $tot"
media=$((tot / numeri))
echo "MEDIA = $media"

# 判断并输出序列类型
if [ "$is_increasing" -eq 1 ]; then
    echo "the sequence is increasing"
elif [ "$is_decreasing" -eq 1 ]; then
    echo "the sequence is decreasing"
else
    echo "the sequence is neither increasing nor decreasing"
fi

关键逻辑说明

  1. 边界检查:先判断输入参数数量,不足2个直接报错退出
  2. 趋势标记初始化:先假设序列既是递增又是递减,后续通过比较推翻假设
  3. 相邻数字比较:从第二个数字开始,逐个和前一个数字对比:
    • 当前数更大时,标记序列不是递减
    • 当前数更小时,标记序列不是递增
  4. 最终判断:根据两个标记的状态输出对应序列类型,同时处理既不递增也不递减的情况

测试示例

  • 输入:./script.sh 1 2 4
    输出:
    TOTALE = 7
    MEDIA = 2
    the sequence is increasing
    
  • 输入:./script.sh 4 3 2
    输出:
    TOTALE = 9
    MEDIA = 3
    the sequence is decreasing
    
  • 输入:./script.sh 1 3 2
    输出:
    TOTALE = 6
    MEDIA = 2
    the sequence is neither increasing nor decreasing
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:55:20