您的位置:首页 > 编程语言

2014微软编程一小时题目1 : Arithmetic Expression

2014-04-16 11:01 357 查看
Arithmetic Expression

时间限制: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


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

int main()
{
//input n
int n;
cin >> n;
if(n < 1 || n > 50000)
return -1;

//input a op b
vector<double> v;
int a ,b = 0;
char op;
double distance = 10000000;//表示和9的距离

while(n-- > 0 && cin >> a >> op >> b )
{

switch (op)
{
case '+' :
v.push_back(fabs((double)(a + b - 9)));
case '-' :
v.push_back(fabs((double)(a - b - 9)));
case '*' :
v.push_back(fabs((double)(a * b - 9)));
case '/' :
v.push_back(fabs((double)a / (double)b - 9));
}
}

//比较distance谁小
double small = v[0];
vector<double>::difference_type number = 0;
for(vector<double>::iterator iter = v.begin() + 1 ; iter != v.end(); ++iter)
{
if((*iter) < small)
{
small = *iter;
number = iter - v.begin();
}
}

cout << number +1 << endl;

//system("pause");//在GCC中编译这个程序的时候一定要加上stdlib.h这个头文件才能编译这一句
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: