sicily 1017

题目在这里1017

二分法求高次方程的根,题目说跟在[0, 1]之间,那么f(0)*f(1)肯定小于0。用一个函数单独计算f,再用一个函数调用f,程序也就很简单了。最后提一下,提交了几次,都出现Presentation Error,删了几个\n,还是有问题,到网上找答案,发现要加一条判断:

if (count > 1)
	cout << endl;
具体什么原因,我也不知道,从题目里没看出现。。

下面是我的代码,仅供参考:

#include<iostream>
#include<vector>
#include<math.h>
#include<stdio.h>
using namespace std;

#define EPS 1e-7

int dcmp(double a, double b)
{
	if (a - b < -EPS)
		return -1;
	else if (a - b > EPS)
		return 1;
	return 0;
}

struct Node
{
	int	month;
	int degree;
	double amount;

	Node(int month, double amount)
	{
		this->month = month;
		this->amount = amount;
	}
};

vector<Node> node;
double total;

int f(double rate)
{
	double sum = 0.0;
	for (int i = 0; i < node.size(); i++)
	{
		sum += node[i].amount * pow(1 + rate, node[i].degree);
	}
	return dcmp(total, sum);
}

double ans()
{
	double head = 1.0, tail = 0.0, mid = tail;
	int i = 20;
	do{
		if (f(head) * f(mid) < 0)
			tail = mid;
		else if (f(mid) * f(tail) < 0)
			head = mid;
		else if (f(mid) == 0)
			return mid;
		mid = (head + tail) / 2;
	} while (i--);
	return mid;
}

int main()
{
	int n, month, count = 0;
	double amount;
	while (cin >> n && n != -1)
	{
		count++;
		for (int i = 0; i < n ; i++)
		{
			cin >> month >> amount;
			node.push_back(Node(month, amount));
		}

		cin >> month >> total;
		for (int i = 0; i < n; i++)
		{
			node[i].degree = month - node[i].month + 1;
		}
		if (count > 1)
			cout << endl;

		printf("Case %d: %.5lf\n", count, ans());
			
		node.clear();
	}
	//system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值