计算2[C++]的幂的不希望的结果
Undesired results from calculating powers of 2 [C++]
好吧,我的头撞不动桌子了。我正试图通过在"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’的矢量。你会发现这样的代码也更好。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 为什么这个涉及 std::enable_if 的模板元函数会产生不希望的结果?
- 计算2[C++]的幂的不希望的结果