解题思路:
注意事项:
参考代码:
高精减法,高精加法,高精乘法呀等等都差不多:
#include <iostream> #include <string> #include <cstring> #include <algorithm> using namespace std; /* * 函数:实现两数相乘,并在合适位置插入小数点,posDot为两数小数位数之和 */ void big_multi(const char *str1,const char *str2,int posDot) { int i,j; int len1=strlen(str1); int len2=strlen(str2); int rlen=len1+len2; int *pResult = new int[rlen]; //分配一个数组存储计算结果,大小为两数的位数之和 memset(pResult,0,rlen*sizeof(int)); //逐位相乘并放在相应位置,pResult[0]存放最终的进位,所以计算时是pResult[i+j+1] for(i=0;i<len1;++i) { for(j=0;j<len2;++j) pResult[i+j+1]+=(str1[i]-'0')*(str2[j]-'0'); } //判断逐位相乘的结果是否大于10,如果大于10要从后向前进位 for(i=rlen-1;i>0;--i) { int t=pResult[i]; if(t>9) { pResult[i-1] += t/10; pResult[i]=t%10; } } //判断结果开头是否是以0开头的,如果是要去掉 i=0; while(pResult[i]==0) i++; //小数点位置应为从后往前posDot位 j=i; while(j<rlen) { if(j==rlen-posDot) cout<<"."; cout<<pResult[j]; j++; } cout<<endl; } int main() { string s1,s2; int pos1,pos2,posDot; while(cin>>s1>>s2) { if(s1=="quit") break; pos1=s1.find("."); pos2=s2.find("."); //计算两数最终相乘结果的小数位数,有3种情况如下 //两数都有小数点的情况 if(pos1!=string::npos && pos2!=string::npos) posDot = s1.length()+s2.length()-pos1-pos2-2; //其中一个有小数点的情况 else if (pos2!=string::npos) posDot = s2.length()-pos2-1; //其中一个有小数点的情况 else if (pos1!=string::npos) posDot = s1.length()-pos1-1; //在相乘之前,先把两数中的小数点去掉,用stl的remove_if函数 string::iterator newEnd1=remove_if(s1.begin(),s1.end(),bind2nd(equal_to<char>(),'.')); string::iterator newEnd2=remove_if(s2.begin(),s2.end(),bind2nd(equal_to<char>(),'.')); //去年小数点后,还要把新字符串结尾和原字符串结尾之间的多余字符删除 s1.erase(newEnd1,s1.end()); s2.erase(newEnd2,s2.end()); const char *str1=s1.c_str(); const char *str2=s2.c_str(); //cout<<str1<<" "<<str2<<" "<<posDot<<endl; big_multi(str1,str2,posDot); } return 0; }
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题6.6 (C++代码)浏览:695 |
IP判断 (C语言代码)浏览:1414 |
点我有惊喜!你懂得!浏览:1401 |
C语言程序设计教程(第三版)课后习题8.1 (Java代码)浏览:775 |
C语言程序设计教程(第三版)课后习题11.3 (C语言代码)浏览:1051 |
C语言程序设计教程(第三版)课后习题6.7 (C语言代码)浏览:626 |
Tom数 (C++代码)浏览:825 |
C语言程序设计教程(第三版)课后习题6.9 (C语言代码)浏览:532 |
C语言程序设计教程(第三版)课后习题6.5 (C语言代码)浏览:624 |
C语言程序设计教程(第三版)课后习题11.1 (C语言代码)浏览:609 |