目录

算术函数(Arithmetic Functions)

AWK具有以下内置算术功能 -

atan2(y, x)

它以弧度为单位返回(y/x)的反正切值。 以下示例演示了这一点 -

例子 (Example)

[jerry]$ 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
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

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

cos(expr)

此函数返回expr的余弦值,以弧度表示。 以下示例演示了这一点 -

例子 (Example)

[jerry]$ awk 'BEGIN {
   PI = 3.14159265
   param = 60
   result = cos(param * PI/180.0);
   printf "The cosine of %f degrees is %f.\n", param, result
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

The cosine of 60.000000 degrees is 0.500000.

exp(expr)

此函数用于查找变量的指数值。

例子 (Example)

[jerry]$ awk 'BEGIN {
   param = 5
   result = exp(param);
   printf "The exponential value of %f is %f.\n", param, result
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

The exponential value of 5.000000 is 148.413159.

int(expr)

此函数将expr截断为整数值。 以下示例演示了这一点 -

[jerry]$ awk 'BEGIN {
   param = 5.12345
   result = int(param)
   print "Truncated value =", result
}'

执行此代码时,您将获得以下结果 -

Truncated value = 5

log(expr)

此函数计算变量的自然对数。

例子 (Example)

[jerry]$ awk 'BEGIN {
   param = 5.5
   result = log (param)
   printf "log(%f) = %f\n", param, result
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

log(5.500000) = 1.704748

rand

此函数返回0到1之间的随机数N,使得0 <= N <1。例如,以下示例生成三个随机数

例子 (Example)

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

执行此代码时,您将获得以下结果 -

输出 (Output)

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

sin(expr)

此函数返回expr的正弦值,以弧度表示。 以下示例演示了这一点 -

例子 (Example)

[jerry]$ awk 'BEGIN {
   PI = 3.14159265
   param = 30.0
   result = sin(param * PI /180)
   printf "The sine of %f degrees is %f.\n", param, result
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

The sine of 30.000000 degrees is 0.500000.

sqrt(expr)

此函数返回expr平方根。

例子 (Example)

[jerry]$ awk 'BEGIN {
   param = 1024.0
   result = sqrt(param)
   printf "sqrt(%f) = %f\n", param, result
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

sqrt(1024.000000) = 32.000000

srand([expr])

此函数使用种子值生成随机数。 它使用expr作为随机数生成器的新种子。 在没有expr的情况下,它使用时间作为种子值。

例子 (Example)

[jerry]$ awk 'BEGIN {
   param = 10
   printf "srand() = %d\n", srand()
   printf "srand(%d) = %d\n", param, srand(param)
}'

执行此代码时,您将获得以下结果 -

输出 (Output)

srand() = 1
srand(10) = 1417959587
↑回到顶部↑
WIKI教程 @2018