zoukankan      html  css  js  c++  java
  • bc显示小数点前的0

    bc是强大而常用的计算工具。不过在除法运算时,如果得到的结果值小于1,得到的小数前面的0不存。本篇提供几个常用小数点前缺0的解决方法。

    [root@361way ~]# bc
    bc 1.06.95
    Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
    This is free software with ABSOLUTELY NO WARRANTY.
    For details type `warranty'.
    scale=2; 1/3
    .33
    

    打开bc进入交互模式,我们键入scale=2; 1/3 回车,看到结果0.33前的0没有---注意此处保留小数点人2位 scale=2不能少,少了结果为是0 。

    解决方法如下:

    #!/bin/bash
    #方法1
    res1=$(printf "%.2f" `echo "scale=2;1/3"|bc`)
    res2=$(printf "%.2f" `echo "scale=2;5/3"|bc`)
    #方法2
    #v=$(echo $big $small | awk '{ printf "%0.2f
    " ,$1/$2}')
    v1=$(echo 1 3 | awk '{ printf "%0.2f
    " ,$1/$2}')
    v2=$(echo 5 3 | awk '{ printf "%0.2f
    " ,$1/$2}')
    #方法3
    mem1=`echo "scale=2; a=1/3; if (length(a)==scale(a)) print 0;print a "|bc`
    mem2=`echo "scale=2; a=5/3; if (length(a)==scale(a)) print 0;print a "|bc`
    echo res1 is $res1
    echo res2 is $res2
    echo v1 is $v1
    echo v2 is $v2
    echo mem1 is $mem1
    echo mem2 is $mem2
    

    这里提供了三种方法,其中第方法1、方法3使用的bc处理,方法2使用的awk处理。执行输出结果我们看下:

    [root@361way shell]# sh bc_point_zero.sh
    res1 is 0.33
    res2 is 1.66
    v1 is 0.33
    v2 is 1.67
    mem1 is 0.33
    mem2 is 1.66
    

    三种方法我们可以看到,方法1、方法3对小数点后面的值不会四舍五入,而方法2(awk)方法使用printf 时会对小数点(浮点运算)的值四舍五入进位。所以浮点运行时还是建议使用awk处理。不过在取整数时,awk默认也是不会四舍五入的。

    # echo 5 3 | awk '{ printf "%d
    " ,$1/$2}'
    1
    # echo 5 3 | awk '{ printf "%d
    " ,$1/$2+0.5}'
    2
    # echo 4 3 | awk '{ printf "%d
    " ,$1/$2+0.5}'
    1
    

    awk在取整数运算时,是需要加0.5进行进位的。

  • 相关阅读:
    Codeforces Round #319 (Div. 2) D
    因为网络请求是 异步的,
    ios真蛋疼,
    单例模式的两种实现,
    jump, jump,
    一点 误删,
    关于代理,
    button上的两个手势,
    数据,
    header 的蓝色,
  • 原文地址:https://www.cnblogs.com/muahao/p/6599891.html
Copyright © 2011-2022 走看看