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

 

程序:

 1 #include<iostream>
 2 #include<string>
 3 #include<stdlib.h>
 4 #include<math.h>
 5 using namespace std;
 6 
 7 double caluculate(double a, double b, char op)
 8 {
 9  if(op == '+')
10  {
11      return a + b;
12  }
13  else if(op == '-')
14  {
15      return a - b;
16  }
17  else if(op == '*')
18  {
19      return (double)(a * b);
20  }
21  else if(op == '/')
22  {
23      return (double)(a / b);
24  }
25 }
26 
27 int main(void)
28 {
29     int amount = 0;
30     cin>>amount;
31     double tmpmin = 2147483647;
32     int position = -1;
33     for(int i=0; i<amount; ++i)
34     {
35         double a,b;
36         char op;
37         cin>>a;
38         cin>>op;
39         cin>>b;
40         double tmpresult = caluculate(a,b,op);
41         double tmp_result = fabs(9-tmpresult);
42         if(tmp_result < tmpmin)
43         {
44             tmpmin = tmp_result;
45             position = i+1;
46         }
47     }
48 
49     cout<<position<<endl;
50 
51     return 0;
52 }

遇到的问题:

  • 一开始没有发现结果应该是double的,int型的话会导致除法的小数位看不到
  • 刚开始使用了stdlib.h中的abs()函数,后来发现应该用math.h中的fabs(),看来自己对math.h中的许多函数都不是很熟悉,不能熟练应用,随后补充

 

转载于:https://www.cnblogs.com/bugking/p/3647559.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值