c++ - 计算 2 的幂的意外结果 [C++]

标签 c++ debugging loops vector

好吧,我的头撞到 table 上了。我正在尝试通过将数字保存在“char” vector 中来计算 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)”部分,我将一个数字推到 vector 的前面也能正常工作,因为我们“进位了 1”以得到两位数.让我们继续:

C:\MyApps\program 5
52

什么?

C:\MyApps\program 6
26

什么什么?

C:\MyApps\program 654
84
C:\MyApps\program 654444
00

它永远不会达到三位数...这到底是怎么回事?

最佳答案

您正在将 atoi 应用于非空终止字符串。实际上,它在内存中看起来很像一个以 null 结尾的字符串,但不是您真正希望它看起来的样子。

解决此问题的最简洁方法可能是在 vector 中存储实际数字值 0..9 而不是 ASCII“0”..“9”。您会发现这样的代码也更好。

关于c++ - 计算 2 的幂的意外结果 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11421140/

相关文章:

c++ - 返回值的初始化应该忽略自动对象的常量性

c - 知道程序执行的确切行

python - 模块未找到错误 : No module named 'xxxdjango'

c - 尝试使用 free() 来了解它是如何工作的

r - 为什么在 rmarkdown 中循环时数据表不打印?

performance - 如何计算已创建算法的理论运行时间?

c++ - 结构错误 "uninitialized reference member"

c++ - 有没有办法强制引用左值?

c++ - 选择多个表 MySQL

javascript - 找到数组中最长的不重复元素,然后返回其原始值