zoukankan      html  css  js  c++  java
  • 模板:高精度浮点数相乘

     1 #include <string>
     2 #include <vector>
     3 #include <algorithm>
     4 
     5 string mul(string str1,string str2)
     6 {
     7     vector<int> v_res(str1.size()+str2.size(),0);
     8     string::size_type i,j;
     9     vector<int>::size_type k,p;
    10 
    11     reverse(str1.begin(),str1.end());
    12     reverse(str2.begin(),str2.end());
    13     for(i = 0; i != str1.size(); ++i)
    14     {
    15         for(j = 0; j != str2.size(); ++j)
    16         {
    17             v_res[i+j] += (str1[i]-'0') * (str2[j] - '0');
    18         }
    19     }
    20     for(k = 0; k != v_res.size() - 1; ++k)
    21     {
    22         v_res[k+1] += v_res[k] / 10;
    23         v_res[k] = v_res[k] % 10;
    24     }
    25 
    26     for(p = v_res.size() - 1; p != -1; --p)
    27     {
    28         if(v_res[p] != 0) break;
    29     }
    30     if(p == -1) p = 0;
    31 
    32     string s_res(p+1,'0');
    33     for(k = p; k != -1; --k) s_res[p-k] = char(v_res[k] + '0');
    34     
    35 
    36     return s_res;
    37 
    38 }
    39 
    40 string real_mul(string str1,string str2)
    41 {
    42     string::size_type idx_str1_point = str1.find(".");
    43     if(idx_str1_point == string::npos)
    44     {
    45         str1 += ".0";
    46         idx_str1_point = str1.find(".");
    47     }
    48     str1.erase(idx_str1_point,1);
    49 
    50     string::size_type idx_str2_point = str2.find(".");
    51     if(idx_str2_point == string::npos)
    52     {
    53         str2 += ".0";
    54         idx_str2_point = str2.find(".");
    55     }
    56     str2.erase(idx_str2_point,1);
    57 
    58     string::size_type dec_res_len = (str1.size() - idx_str1_point) + (str2.size() - idx_str2_point);
    59 
    60     string res = mul(str1,str2);
    61 
    62     if(res.size() < dec_res_len + 1)
    63     {
    64         res = string(dec_res_len + 1 - res.size(),'0') + res;
    65     }
    66 
    67     res.insert(res.size() - dec_res_len,".");
    68 
    69     string::size_type idx_res_tail = res.find_last_not_of("0");
    70     res = res.substr(0,idx_res_tail+1);
    71 
    72     if(res[res.size() - 1] == '.') res.erase(res.size()-1);
    73 
    74     return res;
    75 }
  • 相关阅读:
    Linux_Rsync远程同步备份服务器
    Linux_Rsync远程同步备份服务器
    Linux_VMWare12 Install RHEL7
    Linux_VMWare12 Install RHEL7
    Linux_SquidProxyServer代理服务器
    Linux_SquidProxyServer代理服务器
    Linux_LAMP 最强大的动态网站解决方案
    Ozone Native ACL的应用
    Ozone Audit Log解析工具的应用
    Ozone数据探查服务Recon2.0设计
  • 原文地址:https://www.cnblogs.com/mobileliker/p/3546536.html
Copyright © 2011-2022 走看看