原题如下:
题目1 : Arithmetic Expression
时间限制:
2000ms
单点时限:
200ms
内存限制:
256MB
-
4 901 / 100 3 * 3 2 + 6 8 - -1
样例输出
-
2
描述
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.
自己编写的源码:
#define _CRT_SECURE_NO_DEPRECATE
#include"stdafx.h"
#include <stdio.h>
#include<math.h>
int main(){
int N;
int a,b,index = 0;
char c;
double result,min = 32767;
scanf("%d",&N);
for(int i = 0; i < N;i++){
scanf("%d %c %d",&a,&c,&b);
if(c == '+')
result = a + b;
else if(c == '-')
result = a - b;
else if(c == '*')
result = a * b;
else
result = (double)a / b;
double temp = fabs(result - 9);
if(temp < min){
min = temp;
index = i + 1;
}
}
printf("%d\n",index);
return 0;
}
编程过程中要注意的是由于VS的严格控制,所以在做算法题是最好自己重新编写main()函数,这里涉及宏定义的添加和预定义头文件的设置,具体设置方法见:
http://www.csdn123.com/html/itweb/20130730/29594_29603_29609.htm
另外,在本题中,由于结果保留为double型,所以在做除法前需要先将至少一个操作数转换成double类型
本题没有经过在线测试,有问题还请指正!