当数字超出类型上限就会出现溢出的情形。如果运算结果真的很大,那就需要运用到所谓的高精度运算,即用数组来保存整数,然后模拟手算的形式来实现。但还应考虑一个易用性的问题—如果能像使用int一样方便地使用大整数那该多好!那就是使用struct!
结构体BigInteger可用于储存高精度非负整数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
struct
BigInteger{
static
const
int
BASE = 100000000;
static
const
int
WIDTH = 8;
vector <
int
> s;
BigInteger(
long
long
num=0){*
this
=num;}
BigInteger operator = {
long
long
num}{
s.clear();
do
{
s.push_back(num % BASE);
num /= BASE;
}
while
(num > 0);
return
*
this
;
}
BigInterger operator ={
const
string& str}{
//赋值运算符
s.clear();
int
x,len=(str.length()-1) / WIDTH + 1;
for
(
int
i=0; i<len;i++){
int
end = str.length()-i*WIDTH;
int
start = max(0,end-WIDTH);
scanf
(str.substr(start,end-start).c_str(),
"%d"
,&x);
s.push_back(x);
}
return
*
this
;
}
};
|
其中,s用来保存大整数的各个位数。例如,若要表示1234,则s={4,3,2,1}。用vector而非数组保存数字的好处显而易见:不用关心这个整数多少为。
上诉代码还有两点需要说明,一是static const int BASE = 100000000 ,其作用是声明一个“属于BigInteger”的常数。这个常数不属于任何BigIntrger类型的结构体变量,而是属于BigInteger这个”类型“的,因此成为静态成员变量,在声明时需要加static修饰符。静态变量在结构体外部使用需要写成 “结构体面::静态成员变量名”。
nike官網 中山网站建设 中山SEO 荆州SEO 中山跆拳道 中山律师