㈠ linux 除法保留小数
你可以这样
res=$(printf "%.5f" `echo "scale=5;1/3"|bc`)
%.5f 和 scale=5都表示小数点后面取5位
㈡ linux 小数点如何相加
shell不可直接进行小数运算,可以用去其他方法,这是我想到的
1:用bc方法,你可以去查内查
echo $us+$sy | bc
如我的结果容
# echo $a
8.8
# echo $b
9.1
# echo $a+$b | bc
17.9
2:用awk方法
# awk -v a=$a -v b=$b 'BEGIN{print a+b}'
17.9
㈢ 在Linux系统下,编写一个Shell脚本,从键盘读入5个整数,然后显示最大数、最小数、和平均数。
#!/bin/bash
#任意输入5个数,判断最大值,最小值,总和
s=0
read -p "please input:" num
s=$(($s+$num))
max=$num
min=$num
avg=$(($s/5))
for i in `seq 4`
do
read -p "please input:" num
s=$(($s+$num))
if [ $num -le $min ];then
min=$num
fi
if [ $num -ge $max ];then
max=$num
fi
done
echo max:$max min:$min avg:$avg
(3)linux脚本小数扩展阅读:内
for循环:
一般格式为:
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
写成一容行:
for var in item1 item2 ... itemN; do command1; command2… done;
㈣ Linux 在脚本里面使用变量进行计算时怎么才能保留小数位
bc是一个用于数学运算的高级工具,这个精密计算器包含了大量的选项。可以借助它执行浮点数运算并应用一些高级函数:
#!/bin/bash
a=100
b=3
letc=a/b
echo$c
d=`bc<<<'scale=2;100/3'`
echo$d
e=`bc-l<<<'100/3'`
echo$e
上述代码的输出为:
33
33.33
33.33333333333333333333
㈤ linux下如何在shell中执行小数的运算
你可以用计抄算工具bc来算,再导回shell
如:
#!/bin/sh
x=0.02
x=`echo "scale=3;$x+0.02" | bc `
echo $x
如果要控制循环,x<0.06显然是不能用的,但你可以用x<6,然后把最终结果用bc除以100呗~
㈥ Linux求数组长度为10000的浮点数(精确小数点右4位)计算值
既然题主没有说要求用什么语言,那我就用c++11实现了。
#include<iostream>
#include<random>
#include<thread>
#include<chrono>
#include<algorithm>
#include<iomanip>
usingnamespacestd;
constintsize=10000;
floattable[size];
intmain(){
random_deviceengine;
uniform_real_distribution<float>dist(0,1);
floatsum;
for(auto&i:table){
i=dist(engine);
}
autot_start=chrono::system_clock::now();
sum=accumulate(table,table+size,0.0);
autot_end=chrono::system_clock::now();
autoration=std::chrono::ration_cast<std::chrono::microseconds>(t_end-t_start).count();
cout<<"sumofthemainthread:"<<fixed<<setprecision(4)<<sum<<endl;
cout<<"timeelapsed:"<<ration<<"microseconds"<<endl;
floatsum_child[4];
autofun=[&](intindex){
sum_child[index]=accumulate(table+index*size/4,table+(index+1)*size/4,0.0);
};
t_start=chrono::system_clock::now();
threadthrd_table[4]={
thread(fun,0),thread(fun,1),thread(fun,2),thread(fun,3)
};
for(auto&thrd:thrd_table){
thrd.join();
}
sum=0;
sum=accumulate(sum_child,sum_child+4,0.0);
t_end=chrono::system_clock::now();
ration=std::chrono::ration_cast<std::chrono::microseconds>(t_end-t_start).count();
cout<<"sumofchildthreads:"<<fixed<<setprecision(4)<<sum<<endl;
cout<<"timeelapsed:"<<ration<<"microseconds"<<endl;
return0;
}
编译:
g++-std=c++11test.cc-lpthread-otest
运行:
./test
结果:
sumofthemainthread:4976.8721
timeelapsed:0ms
sumofchildthreads:4976.8721
timeelapsed:0ms
由于随机性每次加和的数值不同,但是精确到毫秒时,时间测出来妥妥的都是零。就是数据量太小,实际运行时间在微秒量级,当然看不出来。
精度改为微秒以后:
sumofthemainthread:4957.9878
timeelapsed:113microseconds
sumofchildthreads:4957.9878
timeelapsed:560microseconds
多线程反而比单线程慢,因为启动线程本身也需要时间。
数据量再增大1000倍:
sumofthemainthread:4999892.0000
timeelapsed:25313microseconds
sumofchildthreads:4999892.0000
timeelapsed:8986microseconds
这回看着正常多了吧