bash
  • unix
  • 2010-06-16 46 views 0 likes 
    0

    我正在編寫一個腳本來檢查一個數字是否是Armstrong。這是我的代碼BASH腳本來檢查一個數字是否是Armstrong

    echo "Enter Number" 
    read num 
    sum=0 
    item=$num 
    while [ $item -ne 0 ] 
    do 
    rem='expr $item % 10' 
    cube='expr $rem \* $rem \* $rem' 
    sum='expr $sum + $cube' 
    item='expr $item/10' 
    done 
    if [ $sum -eq $num ] 
    then 
    echo "$num is an Amstrong Number" 
    else 
    echo "$num is not an Amstrong Number" 
    fi 
    

    後,我運行此腳本,

    $ ./arm.sh

    我總是得到這些錯誤

    線5:[:參數太多

    第12行:[:太多的參數

    我在cygwin上。

    回答

    1

    這些是你的expr命令中的直引號。爲了評估一個表達式,你需要使用反引號:

    rem=`expr $item % 10` 
    
    +0

    十分感謝:)這工作。4分鐘去,我會選擇它作爲正確答案:) – 2010-06-16 08:31:39

    +4

    或者最好(爲了可讀性)使用$(...):rem = $(expr $ item%10) – 2010-06-16 08:31:53

    1

    的錯誤是由缺少在[]命令報價:[ "$item" -ne 0 ]。但是,請勿將[]用於算術表達式。 (()):

    while((item!= 0));做...完成

    此外,你的阿姆斯特朗數的計算似乎是錯誤的。你爲什麼要立方體?在這種情況下,你需要檢查num是否有三位數字,不是嗎? http://en.wikipedia.org/wiki/Narcissistic_number

    假設你真正的意思的「阿姆斯特朗數」的標準定義,這應該工作:

    #!/bin/sh -eu 
    
    is_armstrong() { 
        local num digits sum 
        num="$1" 
        case "$num" in 
        # Reject invalid numerals. 
        (*[^0-9]*|0?*) echo "$num: invalid numeral." >&2; return 1;; 
        esac 
        digits=${#num} 
        sum=0 
        while ((num > 0)); do 
        ((sum += (num % 10) ** digits)) 
        ((num /= 10)) 
        done 
        ((sum == $1)) 
    } 
    
    # Prompt the user for a number if none were give on the command line. 
    if (($# == 0)); then 
        read -p "Enter a natural number: " num 
        set -- "$num" 
    fi 
    
    # Process all the numbers. 
    for num in "[email protected]"; do 
        num=$((num + 0)) # canonicalize the numeric representation 
        if is_armstrong "$num"; then 
        echo "$num is an Amstrong Number" 
        else 
        echo "$num is not an Amstrong Number" 
        fi 
    done 
    
    相關問題