# 算术函数

AWK具有以下内置算术函数-

## atan2(y,x) 反正切

```[Learnfk]\$awk 'BEGIN {
PI=3.14159265
x=-10
y=10
result=atan2 (y,x) * 180/PI;

printf "The arc tangent for (x=%f, y=%f) is %f degrees\n", x, y, result
}'```

`The arc tangent for (x=-10.000000, y=10.000000) is 135.000000 degrees`

## cos(expre) 余弦

```[Learnfk]\$awk 'BEGIN {
PI=3.14159265
param=60
result=cos(param * PI/180.0);

printf "The cosine of %f degrees is %f.\n", param, result
}'```

`The cosine of 60.000000 degrees is 0.500000.`

## exp(expr) 指数

```[Learnfk]\$awk 'BEGIN {
param=5
result=exp(param);

printf "The exponential value of %f is %f.\n", param, result
}'```

`The exponential value of 5.000000 is 148.413159.`

## int(expr) 整数

```[Learnfk]\$awk 'BEGIN {
param=5.12345
result=int(param)

print "Truncated value =", result
}'```

`Truncated value=5`

## log(expr) 对数

```[Learnfk]\$awk 'BEGIN {
param=5.5
result=log (param)

printf "log(%f)=%f\n", param, result
}'```

`log(5.500000)=1.704748`

## rand 随机数

```[Learnfk]\$awk 'BEGIN {
print "Random num1 =" , rand()
print "Random num2 =" , rand()
print "Random num3 =" , rand()
}'```

```Random num1=0.237788
Random num2=0.291066
Random num3=0.845814```

## sin(expr) 正弦值

```[Learnfk]\$awk 'BEGIN {
PI=3.14159265
param=30.0
result=sin(param * PI /180)

printf "The sine of %f degrees is %f.\n", param, result
}'```

`The sine of 30.000000 degrees is 0.500000.`

## sqrt(expr) 平方根

```[Learnfk]\$awk 'BEGIN {
param=1024.0
result=sqrt(param)

printf "sqrt(%f)=%f\n", param, result
}'```

`sqrt(1024.000000)=32.000000`

## srand([expr]) 随机数

```[Learnfk]\$awk 'BEGIN {
param=10

printf "srand()=%d\n", srand()
printf "srand(%d)=%d\n", param, srand(param)
}'```

```srand()=1
srand(10)=1417959587```

## 相关推荐

10x程序员工作法 -〔郑晔 - 〕

15-三剑客-awk总结