Unix中的综合功能 [英] Roundup function in Unix

查看:37
本文介绍了Unix中的综合功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下要求

121.36
121.025
121.1
121.000

所需的输出

122
122
122
121

使用的命令

awk -F"." '{if($8>0){print $11}}'

推荐答案

您要的是 ceil()(用于"

What you're asking for is a ceil() (for "ceiling") function. It's important to include zero and negative numbers in your example when you're looking for any kind of rounding function as it's easy to get them wrong so using this input file:

$ cat file
1.999999
1.0
0.000001
0
-0.000001
-1.0
-1.999999

我们可以测试 ceil()函数:

$ awk 'function ceil(x, y){y=int(x); return(x>y?y+1:y)} {print $0,ceil($0)}' file
1.999999 2
1.0 1
0.000001 1
0 0
-0.000001 0
-1.0 -1
-1.999999 -1

和相反的 floor()函数:

$ awk 'function floor(x, y){y=int(x); return(x<y?y-1:y)} {print $0,floor($0)}' file
1.999999 1
1.0 1
0.000001 0
0 0
-0.000001 -1
-1.0 -1
-1.999999 -2

以上方法之所以有效,是因为 int()截断为零(根据GNU awk手册):

The above works because int() truncates towards zero (from the GNU awk manual):

int(x)
    Return the nearest integer to x, located between x and zero and
    truncated toward zero. For example, int(3) is 3, int(3.9) is 3,
    int(-3.9) is -3, and int(-3) is -3 as well.

所以负数的 int()已经完成了上限函数所需的功能,即四舍五入,如果 int()舍入一个正数.

so int() of a negative number already does what you want for a ceiling function, i.e. round up, and you just have to add 1 to the result if int() rounded down a positive number.

我在示例中使用了 0.000001 等,以避免人们误测测试解决方案,该解决方案添加了诸如 0.9 之类的数字,然后添加了 int().

I used 0.000001, etc. in the samples to avoid people getting a false positive testing a solution that adds some number like 0.9 and then int()ing.

还请注意, ceil()可以缩写为:

Also note that ceil() could be abbreviated to:

function ceil(x){return int(x)+(x>int(x))}

但是为了清楚起见,我如上所述编写(不清楚/很明显 x> int(x)的结果是1还是0)和效率(仅调用 int()一次,而不是两次).

but I wrote it as above for clarity (it's not clear/obvious that the result of x>int(x) is 1 or 0) and efficiency (only call int() once instead of twice).

这篇关于Unix中的综合功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆