计算2[C++]的幂的不希望的结果

Undesired results from calculating powers of 2 [C++]

本文关键字:希望 结果 C++ 计算      更新时间:2023-10-16

好吧,我的头撞不动桌子了。我正试图通过在"char"的向量中保持数字来计算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:MyAppsprogram 2
4
C:MyAppsprogram 3
8
C:MyAppsprogram 4
16

好吧,到目前为止看起来不错。。。即使是我的"if(carry==1)"部分,我把一个数字推到向量的前面,也能起作用,因为我们"carry the 1"变成了两位数。让我们继续:

C:MyAppsprogram 5
52

什么?

C:MyAppsprogram 6
26

什么?

C:MyAppsprogram 654
84
C:MyAppsprogram 654444
00

它永远不会达到三位数。。。到底发生了什么?

您正在将atoi应用于非以null结尾的字符串。在实践中,它在内存中可能看起来像一个以null结尾的字符串,但不是您真正想要的字符串。

解决此问题的最干净方法可能是存储实际数字值0..9,而不是ASCII"0..."9’的矢量。你会发现这样的代码也更好。