您的位置:首页 > 其它

Arithmetic Expression

2014-04-05 21:06 183 查看
时间限制:2000ms
单点时限:200ms
内存限制:256MB

描述

Given N arithmetic expressions, can you tell whose result is closest to 9?

输入

Line 1: N (1 <= N <= 50000).
Line 2..N+1: Each line contains an expression in the format of "a op b" where a, b are integers (-10000 <= a, b <= 10000) and op is one of addition (+), subtraction (-), multiplication (*) and division (/). There is no "divided by zero" expression.

输出

The index of expression whose result is closest to 9. If there are more than one such expressions, output the smallest index.

样例输入
4
901 / 100
3 * 3
2 + 6
8 - -1

样例输出
2


[b]程序:[/b]

#include<iostream>
#include<string>
#include<stdlib.h>
#include<math.h>
using namespace std;

double caluculate(double a, double b, char op)
{
if(op == '+')
{
return a + b;
}
else if(op == '-')
{
return a - b;
}
else if(op == '*')
{
return (double)(a * b);
}
else if(op == '/')
{
return (double)(a / b);
}
}

int main(void)
{
int amount = 0;
cin>>amount;
double tmpmin = 2147483647;
int position = -1;
for(int i=0; i<amount; ++i)
{
double a,b;
char op;
cin>>a;
cin>>op;
cin>>b;
double tmpresult = caluculate(a,b,op);
double tmp_result = fabs(9-tmpresult);
if(tmp_result < tmpmin)
{
tmpmin = tmp_result;
position = i+1;
}
}

cout<<position<<endl;

return 0;
}


[b]遇到的问题:[/b]

一开始没有发现结果应该是double的,int型的话会导致除法的小数位看不到

刚开始使用了stdlib.h中的abs()函数,后来发现应该用math.h中的fabs(),看来自己对math.h中的许多函数都不是很熟悉,不能熟练应用,随后补充
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: