【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;
}





相关文章
|
6月前
|
存储
easy_Maze 题解
easy_Maze 题解
20 1
|
6月前
|
机器学习/深度学习
poj 2155 Matrix (二维树状数组)
这是楼教主出的二维线段树或者是二维树状数组的题,题意很简单,就是有个n*n的矩阵,初始值都是0,然后给你两个操作,一个是给你左上角和右下角的坐标,把这个长方形的区间所有元素反取反(0变1 1变0),另一个是求某个具体坐标的值。 这里我用了二维的线树状数组,一维树状数组可以解决区间更新和点查询的问题,这里只需要加一维就可以了,代码比较好写,不过开始犯了很多低级的错误。
18 0
|
11月前
|
存储 测试技术 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.
80 0
Leetcode-Easy 461.Hamming Distance
Leetcode-Easy 461.Hamming Distance
88 0
Leetcode-Easy 461.Hamming Distance
Leetcode-Easy 867.Transpose Matrix
Leetcode-Easy 867.Transpose Matrix
68 0
Leetcode-Easy 70. Climbing Stairs
Leetcode-Easy 70. Climbing Stairs
79 0
Leetcode-Easy 70. Climbing Stairs
|
算法
【POJ 1330 Nearest Common Ancestors】LCA问题 Tarjan算法
题目链接:http://poj.org/problem?id=1330 题意:给定一个n个节点的有根树,以及树中的两个节点u,v,求u,v的最近公共祖先。 数据范围:n [2, 10000] 思路:从树根出发进行后序深度优先遍历,设置vis数组实时记录是否已被访问。
1231 0

热门文章

最新文章