这题过得想呵呵了。。。double型的数很麻烦。。。有一个始终过不了,一直WA,但是学会了另一种double型比较大小的方式。。。
令double eps=1e-9; 然后如果double型的 a和b 比较大小,只需比较他们的差值和eps的大小即可。。。因为double有误差
eg: a-b>eps
AC的代码:
#include <stdio.h>double price[10005];//每天价格double cal(int day,int n)
{//计算第day天,前n天的均价int i;double sum=0;int count=n;for(i=day;count>0;i--){sum+=price[i];count--;}return (double)sum/(double)n;
}void work(int m,int n,int k)
{if(cal(n,m)>cal(n,n))printf("BUY ON DAY %d\n",n);else if(cal(n,m)<cal(n,n))printf("SELL ON DAY %d\n",n);int i;for(i=n+1;i<=k;i++){if(cal(i-1,m)<cal(i-1,n) && cal(i,m)>cal(i,n))printf("BUY ON DAY %d\n",i);else if(cal(i-1,m)>cal(i-1,n) && cal(i,m)<cal(i,n))printf("SELL ON DAY %d\n",i);}
}int main()
{int m,n; //几日均线,且知 m<nint k; //连续多少天scanf("%d%d%d",&m,&n,&k);int i;for(i=1;i<=k;i++)scanf("%lf",&price[i]);work(m,n,k);return 0;
}
一直WA的代码:
#include <stdio.h>double price[10005];//每天价格
bool isOnHand; //手中有股票没有,没有是false
double eps=1e-9;double cal(int day,int n)
{//计算第day天,前n天的均价int i;double sum=0;int count=n;for(i=day;count>0;i--){sum+=price[i];count--;}return (double)sum/(double)n;
}void work(int m,int n,int k)
{int i;for(i=n;i<=k;i++){if(isOnHand==false && cal(i,m)-cal(i,n)>eps){printf("BUY ON DAY %d\n",i);isOnHand=true;}else if(isOnHand==true && cal(i,m)-cal(i,n)<eps){printf("SELL ON DAY %d\n",i);isOnHand=false;}}
}int main()
{int m,n; //几日均线,且知 m<nint k; //连续多少天scanf("%d%d%d",&m,&n,&k);int i;for(i=1;i<=k;i++)scanf("%lf",&price[i]);isOnHand=false;work(m,n,k);return 0;
}