CU很多C的大牛们都是养牛出身的,俺现在也开始学习养牛。
来源:
题目:若一头小母牛,从出生起第四个年头开始每年生一头母牛,按此规律,第n年有多少头母牛?
C 版本:
#include #include int Cow_Sum(int Year) { if(Year < 3) { printf("Cow is 1\n"); exit(0); } int i=2; double Cow0=0,Cow1=1,Cow2=0,Cow3=0; for(i;i<=Year;i++) { Cow0=Cow3; Cow3=Cow2+Cow3; Cow2=Cow1; Cow1=Cow0; } printf("Cow is %0.f\n",Cow1+Cow2+Cow3); return(0); }
main(int argc,char *argv[]) { if(argc < 2) printf("Please input %s year:\n",argv[0]); else { Cow_Sum(atoi(argv[1])); } }
|
shell 版本:
#!/bin/bash [ -z $1 ] && { echo "$0 Year." ;exit 1; } (( $1 < 3 )) && { echo Cow is 1;exit 0; } typeset i=1;Year=${1//[!0-9]/ }
Cow=(0 1 0 0) for((i=2;i<=Year;i++));do Cow[0]=${Cow[3]};Cow[3]=$[Cow[2]+Cow[3]] Cow[2]=${Cow[1]};Cow[1]=${Cow[0]} done echo "Cow is $((Cow[1]+Cow[2]+Cow[3]+Cow[4]))"
|
阅读(1151) | 评论(0) | 转发(0) |