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

微软编程一小时比赛--题目1 : Arithmetic Expression

2014-04-05 20:52 363 查看


题目1 : 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>
using std::endl;
using std::cin;
using std::cout;
//operation的函数
double operation(int a , char op , int b)
{
double result;
if(op == '+')
{
result = a + b;
}else if(op == '-')
{
result = a - b;
}else if(op == '*')
{
result = a * b;
}else{
result = (double)a / (double)b;
}
return result;
}
int main(void)
{
int N;
cin >> N;
//distance 记录每组表达式与目标值的接近程度
double distance = 1000000000;
//保存最后的接近的索引
int index;
int cnt=1;
while(cnt<=N)
{
int a,b;
char op;
//输入每组表达式
cin >> a >> op >> b;
double res;
res = operation(a , op , b);
//计算与目标值的接近程度
double temp = res - 9;
//如果小于0则取反
if(temp < 0)
{
temp = -temp;
}
//比较当前是否最接近如果当前最接近的话则进行替换
if(temp < distance)
{
distance = temp;
index = cnt;
}
cnt++;
}
cout << index << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM 编程之美