1. 程式人生 > >利用C++ string實現任意長度小數、整數之間的加法

利用C++ string實現任意長度小數、整數之間的加法

code include spa ctype empty esp pac space temp

  1 /*
  2 大數的運算1--加法:
  3 利用C++ string實現任意長度小數、整數之間的加法
  4 作者:大大維
  5 2017/5/5
  6 */
  7 #include<iostream>
  8 #include<string>
  9 #include<cctype>
 10 #include<algorithm>
 11 using namespace std;
 12 int main()
 13 {
 14     string num1,num2;
 15     cout<<"
Input num1 , num2:"<<endl; 16 cin>>num1>>num2; 17 string num11,num12,num21,num22; 18 //輸入檢查 19 int tempCnt=0; 20 for(auto c:num1) 21 { 22 if(!isdigit(c)||num1.empty()) 23 { 24 if(c==.&&tempCnt!=1) 25 {
26 ++tempCnt; 27 } 28 else 29 { 30 cout<<"num1: Please input correct form!!!"<<endl; 31 return 0; 32 } 33 } 34 } 35 tempCnt=0; 36 for(auto c:num2) 37 {
38 if(!isdigit(c)||num2.empty()) 39 { 40 if(c==.&&tempCnt!=1) 41 { 42 ++tempCnt; 43 } 44 else 45 { 46 cout<<"num2: Please input correct form!!!"<<endl; 47 return 0; 48 } 49 } 50 } 51 52 //字符串分割(整數部分和小數部分) 53 int i=0; 54 while(i!=num1.size()&&num1[i]!=.) 55 { 56 num11+=num1[i]; 57 ++i; 58 } 59 while(++i!=num1.size()) 60 { 61 num12+=num1[i]; 62 } 63 i=0; 64 while(i!=num2.size()&&num2[i]!=.) 65 { 66 num21+=num2[i]; 67 ++i; 68 } 69 while(++i!=num2.size()) 70 { 71 num22+=num2[i]; 72 } 73 if(num11.empty()) 74 num11+=0; 75 if(num12.empty()) 76 num12+=0; 77 if(num21.empty()) 78 num21+=0; 79 if(num22.empty()) 80 num22+=0; 81 82 83 //小數部分計算 84 string &strLong2=num12,&strShort2=num22; 85 if(strLong2.size()<strShort2.size()) 86 { 87 string strTemp=strLong2; 88 strLong2=strShort2; 89 strShort2=strTemp; 90 } 91 //補0 92 for(int i=strShort2.size();i<strLong2.size();++i) 93 strShort2+=0; 94 //反轉字符串 95 reverse(strLong2.begin(),strLong2.end()); 96 reverse(strShort2.begin(),strShort2.end()); 97 //小數部分進行加法計算 98 string strRes2(strLong2.size(),0); 99 int carry=0;//進位 100 for(int i=0;i!=strLong2.size();++i) 101 { 102 int a=strShort2[i]-0,b=strLong2[i]-0; 103 a=a+b+carry; 104 carry=a/10; 105 strRes2[i]=(a%10)+0; 106 } 107 //反轉回來 108 reverse(strRes2.begin(),strRes2.end()); 109 110 111 //整數部分計算 112 //反轉字符串 113 string &strLong1=num11,&strShort1=num21; 114 if(strLong1.size()<strShort1.size()) 115 { 116 string strTemp=strLong1; 117 strLong1=strShort1; 118 strShort1=strTemp; 119 } 120 reverse(strLong1.begin(),strLong1.end()); 121 reverse(strShort1.begin(),strShort1.end()); 122 123 124 string strRes1(strLong1.size(),0); 125 for(int i=0;i!=strShort1.size();++i) 126 { 127 int a=strShort1[i]-0,b=strLong1[i]-0; 128 a=a+b+carry; 129 carry=a/10; 130 strRes1[i]=(a%10)+0; 131 } 132 for(int i=strShort1.size();i!=strLong1.size();++i) 133 { 134 int b=strLong1[i]-0; 135 b+=carry; 136 carry=b/10; 137 strRes1[i]=b%10+0; 138 } 139 if(carry) 140 { 141 strRes1+=(carry+0); 142 } 143 //反轉回來 144 reverse(strRes1.begin(),strRes1.end()); 145 146 147 //合並整數部分和小數部分 148 string strRes=strRes1+.+strRes2; 149 cout<<"The result = "<<strRes<<endl; 150 }

利用C++ string實現任意長度小數、整數之間的加法