![]() |
#2
pangding2012-08-05 14:10
|

#include "Add.h"
#include <iostream>
#include <vector>
using namespace std;
bool Add::ForwardBool = false; //赋初值为 "没有进位"
void Add::Input()
{
cout << "input two numbers :"<<endl;
cin >> str1 >>str2;
}
void Add::add()
{
int str1Len = str1.length();
int str2Len = str2.length();
int str3Len = (str1Len > str2Len) ? str1Len : str2Len;
//使输入的数字同等长度
if(str1Len < str2Len)
{
for(int i = str1Len;i < str2Len;i++)
{
str1.insert(0,"0");
}
}
else
{
for(int i = str2Len;i < str1Len;i++)
{
str2.insert(0,"0");
}
}
//每一位进行相加
for(int i = str3Len-1; i >= 0 ;i--)
{
string str1Temp,str2Temp;
str1Temp = str1[i];
str2Temp = str2[i];
int strTemp = atoi(str1Temp.c_str())+atoi(str2Temp.c_str());//atoi将字符型转换成整型
if(true == ForwardBool) // 如果有进位 42
{
strTemp = strTemp +1;
ForwardBool = false;
}
if(strTemp >9) //如果两个数加起来大于9
{
if(0 != i) //如果不是数字的第一位,就采取进位方法,若是数字的第一位,就不进位了
{
strTemp = strTemp%10;
ForwardBool = true;// 52
}
}
vecResult.push_back(strTemp);//结果保存在vector中
}
}
void Add::Output()
{
vector <int> ::reverse_iterator reverse_it; //倒序的方式输出vector
for(reverse_it = vecResult.rbegin(); reverse_it != vecResult.rend() ;reverse_it ++)
{
cout << *reverse_it;
}
cout <<endl;
vecResult.clear(); //vector清空
}
请问下42-52行什么意思啊?谢了哈#include <iostream>
#include <vector>
using namespace std;
bool Add::ForwardBool = false; //赋初值为 "没有进位"
void Add::Input()
{
cout << "input two numbers :"<<endl;
cin >> str1 >>str2;
}
void Add::add()
{
int str1Len = str1.length();
int str2Len = str2.length();
int str3Len = (str1Len > str2Len) ? str1Len : str2Len;
//使输入的数字同等长度
if(str1Len < str2Len)
{
for(int i = str1Len;i < str2Len;i++)
{
str1.insert(0,"0");
}
}
else
{
for(int i = str2Len;i < str1Len;i++)
{
str2.insert(0,"0");
}
}
//每一位进行相加
for(int i = str3Len-1; i >= 0 ;i--)
{
string str1Temp,str2Temp;
str1Temp = str1[i];
str2Temp = str2[i];
int strTemp = atoi(str1Temp.c_str())+atoi(str2Temp.c_str());//atoi将字符型转换成整型
if(true == ForwardBool) // 如果有进位 42
{
strTemp = strTemp +1;
ForwardBool = false;
}
if(strTemp >9) //如果两个数加起来大于9
{
if(0 != i) //如果不是数字的第一位,就采取进位方法,若是数字的第一位,就不进位了
{
strTemp = strTemp%10;
ForwardBool = true;// 52
}
}
vecResult.push_back(strTemp);//结果保存在vector中
}
}
void Add::Output()
{
vector <int> ::reverse_iterator reverse_it; //倒序的方式输出vector
for(reverse_it = vecResult.rbegin(); reverse_it != vecResult.rend() ;reverse_it ++)
{
cout << *reverse_it;
}
cout <<endl;
vecResult.clear(); //vector清空
}
已经标注了
[ 本帖最后由 a99875984 于 2012-8-5 13:26 编辑 ]