首页 > 解决方案 > C++:尝试在二进制到十进制转换器中多次将非常大的整数加在一起,而您的输入是字符串值

问题描述

template <class Type>
string MyStack<Type>::binaryToDecimal2(string n)
{
//variable declaration and initialization
string dec = "";
MyStack<string> stk;
for (unsigned int i = 0; i < n.length(); i++)
{
    string s = to_string((n[i] - '0') * pow(2, (n.length() - i - 1)));
    stk.push(s);
}
while (!stk.isEmptyStack()){
    string item;
    item = stk.top();
    stk.pop();
    cout << item << endl;
}
return dec;
}

我如何能够更改 binaryToDecimal2 以便成功地将我的字符串加在一起而不会丢失数据?我已经尝试制作要加在一起的无符号整数的元素,但是如果值太大,我得到的值是不正确的。在此处输入图像描述

在照片中,您输入一个二进制数,表示等效十进制数的行是:当我使用整数时。带有很多小数的数字是在while循环内从我的堆栈中输出的时候。我如何能够添加所有这些数字并将它们放在 dec 中以输出?

标签: c++data-structures

解决方案


1) 结果是否不准确或完全错误?数字必须有多大才能“太大”?我无法运行您的代码,因为它不完整,num已定义但从未使用过。如果您尝试分配大于 2³² 的数字,则它当然无法捕获num

2) std::pow 返回一个浮点数,然后将其转换为字符串。执行后

std::string n = "10100";
std::vector<std::string> stk;
for (unsigned int i = 0; i < n.length(); i++)
{
    std::string s = std::to_string((n[i] - '0') * std::pow(2, (n.length() - i - 1)));
    stk.push_back(s);
}

stk

16.000000                                                                                                                    
0.000000                                                                                                                     
4.000000                                                                                                                     
0.000000                                                                                                                     
0.000000  

但我很确定findSum希望传递的字符串不包含点。


推荐阅读