Linux中awk命令正确的求最大值,最小值,平

Linux中awk命令正确的求最大值,最小值,平,第1张

test.txt文件内容:

9

11

35

21

42

118

最大值

awk 'BEGIN {max = 0} {if ($1+0 >max+0) max=$1} END {print "Max=", max}' test.txt

Max= 118

求最小值:

awk 'BEGIN {min = 65536} {if ($1+0 <min+0) min=$1} END {print "Min=", min}' test.txt

Min= 9

求和

cat test.txt|awk '{sum+=$1} END {print "Sum= ", sum}'

Sum= 236

平均值

cat test.txt|awk '{sum+=$1} END {print "Avg= ", sum/NR}'

Avg= 39.3333

(test1.c)

#include <stdio.h>

void func1(int *arr, int n, int *max_num, int *min_num) {

      if (n == 0) return

      *min_num = *max_num = arr[0]

      if (n == 1) return

      for (int i = 0i <ni++) {

              if (arr[i] >*max_num) *max_num = arr[i]

              if (arr[i] <*min_num) *min_num = arr[i]

      }

}

int main() {

      int arr[] = {1,2,3,4,5}

      int min_num, max_num

      func1(arr, 5, &max_num, &min_num)

      printf("min=%d, max=%d\n", min_num, max_num)

      return 0

}

(Makefile)

test1.out: test1.c

      gcc test1.c -o test1.out

#!/bin/bash

#任意输入5个数,判断最大值,最小值,总和

s=0

read-p"pleaseinput:"num

s=$(($s+$num))

max=$num

min=$num

avg=$(($s/5))

foriin`seq4`

do

read-p"pleaseinput:"num

s=$(($s+$num))

if[$num-le$min]then

min=$num

fi

if[$num-ge$max]then

max=$num

fi

done

echomax:$maxmin:$minavg:$avg

扩展资料:

for循环:

一般格式为:

forvarinitem1item2...itemN

do

command1

command2

...

commandN

done

写成一行:

forvarinitem1item2...itemNdocommand1command2?done


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8961919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-23
下一篇 2023-04-23

发表评论

登录后才能评论

评论列表(0条)

保存