ACM訓練題

微軟編程在線一小時:

題目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
//source here
#include<iostream>
using namespace std;

int main(int argc,char **argv)
{
	int num;
	char op;
	long double result=1.79769e+308,tmp;
	int index = 1;
	int num1,num2;
	cin>>num;
	for(int i=0;i<num;i++)
	{
		cin>>num1>>op>>num2;
		switch(op)
		{
		case '+':
						tmp = abs(num1+num2 - 9);
						break;
		case '-':
						tmp = abs(num1-num2 - 9);
						break;
		case '*':
						tmp = abs(num1*num2 - 9);
						break;
		case '/':
						tmp = abs(num1/(double)num2 - 9);
						break;
		default:
			break;
		}
		if (tmp == 0.0)
		{
			index = i+1;
			break;
		}
		if(tmp < result )
		{
			index = i+1;
		}
	}
	printf("%d",index);
}

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