好吧,我已经把头撞在桌子上了。我试图通过将数字保存在 'char's 向量中来计算 2 的巨大幂 [超出 uint64_t 数据类型中能够保存的内容]。这是我的程序,后面是我的实际输出:
/*
This program doubles a very large number by using a vector of char types
Usage: program.exe [number]
Output will be 2^[number]
*/
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
vector<char> BigNum;
BigNum.push_back('2');
int carry=0, digit;
int power=atoi(argv[1]);
power-=1;
for(int x=0;x<power;x++) //Example: going from 16 to 32. x==4
{
for(int y=BigNum.size()-1;y>=0;y--) //Go from BigNum[1] to BigNum[0] ('6' then '1')
{
digit=atoi(&BigNum[y]); //digit = 6, then digit=1
BigNum[y]=(char)(((digit*2+carry)%10)+48); //BigNum[1]=(char)(6*2+0)%10+48 = '2' in char
//BigNum[0]=(char)(1*2+1)%10+48 = '3' in char
carry=digit*2/10; //carry=1, then 0
}
if(carry==1) //does not execute. BigNum=={'3','2'}
{
BigNum.push_back('0');
for(int y=BigNum.size()-1;y>0;y--)
{
BigNum[y]=BigNum[y-1];
}
BigNum[0]='1';
carry=0;
}
}
for(int x=0;x<BigNum.size();x++) cout<<BigNum[x];
}
编译:
g++ program.cpp -o program
所以这是我运行程序时的结果:
C:\MyApps\program 2
4
C:\MyApps\program 3
8
C:\MyApps\program 4
16
好的,到目前为止看起来不错......甚至我的“if(carry == 1)”部分,我将一个数字推到向量的前面,因为我们“携带1”进入两位数。让我们继续:
C:\MyApps\program 5
52
什么?
C:\MyApps\program 6
26
什么什么?
C:\MyApps\program 654
84
C:\MyApps\program 654444
00
它永远不会达到三位数......到底发生了什么?