题目在这里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;
}