微軟2014在線編程一小時活動第一題



題目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::cin;
using std::cout;
using std::endl;

float opFun(int a,int b,char op)
{
	float c=0;
	float a1 = (float)a;
	float b1 = (float)b;
	switch(op)
	{
		case '+':
			c=a1+b1;break;
		case '-':
			c=a1-b1;break;
		case '*':
			c=a1*b1;break;
		case '/':
			c=a1/b1;break;
		default:
			break;
	}
	return c;
}

int main(void)
{
	int a,b,N,flag,i=0;
	float value=0,c,d1,d2;
	char op;
	cin>>N;
	cin>>a>>op>>b;
	value = opFun(a,b,op);
	i++;
	flag = i;

	while(++i<=N)
	{
		cin>>a>>op>>b;
		c = opFun(a,b,op);

		d1 = value-9;
		d2 = c-9;
		d1 = d1<0?-d1:d1;
		d2 = d2<0?-d2:d2;

		if(d1>d2)
		{
			value=c;
			flag = i;
		}
	}
	cout<<flag<<endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章