求阶乘。
学习要点:
1. for循环
2. 输出格式
printf([format_expression],arguments)
printf的格式符:
c -- ASCII character
d -- Decimal integer
e -- Floating point format ([-]d.precisionE[+-]dd)
f -- Floating point format([-]ddd.precision)
g -- e or f conversion, which is shortest, with trailing zeros removed
o -- Unsigned octal value
s -- String
x -- Unsigned hexadecimal number
% -- Literal %
3. Input loop(输入循环),一直到用户输入数字,程序才会自动退出
[@more@]$ cat factorial.awk
awk '
BEGIN{
print "Enter the number: "
}
$1 ~ /[0-9]+/ {
number = $1
factorial = number
for ( x=number-1;x>1;x--)
factorial *= x
printf("The factorial of %d is %gn", number, factorial)
exit
}
$1 !~ /[0-9]+/ {
print "n Invalid entry. Enter a number: "
}'
运行:
$ factorial.awk
Enter the number:
ss
Invalid entry. Enter a number:
5
The factorial of 5 is 120
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/207/viewspace-779722/ ,如需转载,请注明出处,否则将追究法律责任。