华为机试在线训练. 取近似值

题目描述

写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。

正常人解法:

1 #include<iostream>
2 using namespace std;
3 int main(){
4     float num;
5     cin>>num;
6     cout<<int(num+0.5)<<endl;
7     return 0;
8 }

憨憨的解法(me):

 1 #include <iostream>
 2 #include <math.h>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     float num;
 8     cin>>num;
 9     string str='0'+to_string(num);
10     bool carry=false;//是否进位
11     while(str.back()!='.'){
12         if(carry){
13             str.back()++;
14         }
15         if(str.back()>='5'){//5~9
16             str.pop_back();
17             carry=true;
18         }
19         else{//1~4
20             str.pop_back();
21             carry=false;
22         }
23     }
24     str.pop_back();//pop '.'
25     int i=str.size()-1;
26     while(carry){
27         str[i]++;
28         if(str[i]>'9'){
29             str[i]='0';
30             carry=true;
31         }
32         else{
33             carry=false;
34         }
35         --i;
36     }
37     cout<<stoi(str);
38     return 0;
39 }

猜你喜欢

转载自www.cnblogs.com/FdWzy/p/12315620.html