【eps=1e-9】poj 2163 Easy Trading

简介:

这题过得想呵呵了。。。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<n
	int 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<n
	int 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;
}





相关文章
|
4月前
|
Java
HDU-2199-Can you solve this equation
HDU-2199-Can you solve this equation
26 0
|
4月前
|
Java
HDU-2199-Can you solve this equation?
HDU-2199-Can you solve this equation?
30 0
|
存储 测试技术 C++
C++/PTA Easy chemistry
In this question, you need to write a simple program to determine if the given chemical equation is balanced. Balanced means that the amount of elements on both sides of the “=” sign is the same.
94 0
|
存储 C语言
POJ1521---Entropy
POJ1521---Entropy
POJ-1328,Radar Installation(贪心)
POJ-1328,Radar Installation(贪心)
Leetcode-Easy 461.Hamming Distance
Leetcode-Easy 461.Hamming Distance
104 0
Leetcode-Easy 461.Hamming Distance
Leetcode-Easy 867.Transpose Matrix
Leetcode-Easy 867.Transpose Matrix
84 0
HDOJ(HDU) 1898 Sempr == The Best Problem Solver?(水题、、、)
HDOJ(HDU) 1898 Sempr == The Best Problem Solver?(水题、、、)
118 0