杭电 2986题

//map类型的使用和实数比较
//(1)题目要求浮点数只有一位,所以可以采取乘10将结果赋给一个整数,然后进行整数之间的比较
//(2)a < b - epsilon, a <=b as a <= b + epsilon, and a = b becomes |a-b| < epsilon. epsilon取10-9
#include <map>
#include <math.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
 freopen("1.txt","r",stdin);
 int p,q;
 int i,j;
 string party;
 string str;
 double vote;
 double sum;
 //int sum;
 int n;
 string str1(">");
 string str2("<");
 string str3("=");
 string str4(">=");
 string str5("<=");
 string str6("+");
 map<string,double> partymap;
 while(cin>>p>>q)
 {
  partymap.clear(); //此处别忘了map进行初始化
  for(i=0;i<p;++i)
  {
   cin>>party>>vote;
   partymap[party] = vote;
  }
  for(j=1;j<q+1;++j)
  {
   sum = 0;
   cin>>str;
   //利用表达式是否等于<,<=,>,>=,=来判断表达式是否结束
   while(str!=str1 && str!=str2 && str!=str3 && str!=str4 && str!=str5)
   {
    if(str!=str6) 
    {
     sum = sum+partymap[str];
    }
    cin>>str;
   }
   cin>>n;
   if(str==str1)
   {
    //if(sum>n)
    if(sum-n>1e-9)
    {
     cout<<"Guess #"<<j<<" was correct."<<endl;
    }
    else
     cout<<"Guess #"<<j<<" was incorrect."<<endl;
   }
   else if(str==str2)
   {
    //if(sum<n)
    if(n-sum>1e-9)
    {
     cout<<"Guess #"<<j<<" was correct."<<endl;
    }
    else
     cout<<"Guess #"<<j<<" was incorrect."<<endl;
   }
   else if(str==str4)
   {
    //if(sum>=n)
    if(sum+1e-9>=n)
    {
     cout<<"Guess #"<<j<<" was correct."<<endl;
    }
    else
     cout<<"Guess #"<<j<<" was incorrect."<<endl;
   }
   else if(str==str5)
   {
    if(sum<=n+1e-9)
    {
     cout<<"Guess #"<<j<<" was correct."<<endl;
    }
    else
     cout<<"Guess #"<<j<<" was incorrect."<<endl;
   }
   else
   {
    //if(sum==n)
    if(fabs(sum-n)<1e-9) //fabs是对浮点数取绝对值
    {
     cout<<"Guess #"<<j<<" was correct."<<endl;
    }
    else
     cout<<"Guess #"<<j<<" was incorrect."<<endl;
   }
  }
 }
 return 0;
}

你可能感兴趣的:(杭电)