Shell solves the problem of buying chickens: 3 cents can buy 1 rooster, 2 cents can buy a hen, and 1 cent can buy 3 chicks. If you buy 100 chickens for 100 cents, how many roosters, hens, and chickens are there?

Directly on the code:

#!/bin/bash
#题目描述: 3文钱可以买1只公鸡,2文钱可以买一只母鸡,1文钱可以买3只小鸡。用100 文 钱买100 只鸡,那么各有公鸡、母鸡、小鸡
多少只? 
echo -e "\033[1;31m公鸡单价:3\033[0m"
echo -e "\033[1;31m母鸡单价:2\033[0m"
echo -e "\033[1;31m小鸡单价:1/3\033[0m"
for i in {
    
    0..34}; do #100文钱公鸡的数量肯定不会超过34只
    for j in {
    
    0..50}; do #100文钱母鸡的数量肯定不会超过50只
        for z in {
    
    0..100}; do #小鸡便宜,但是只能买100只鸡,所以小鸡最多只是有可能买100只
            if [ $[z%3] -eq 0 ];then #这里做个判断,因为1文钱可以买3只小鸡,所以买的小鸡的只数肯定是3的倍数
                sum=$[i+j+z] #买的鸡的总数
                SUM=$[3*i+2*j+z/3] #买鸡花的钱的总数

                if [ "${sum}" -eq 100 -a "${SUM}" -eq 100 ];then #当满足了买鸡100只,同时花了100文钱,条件成立,输出各种鸡的个数
                    echo 公鸡:$i 母鸡:$j 小鸡:$z
                fi
            fi
        done
    done
done

The output is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44901564/article/details/106377516