c++ - 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 中以输出?
解决方案
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
希望传递的字符串不包含点。
推荐阅读
- c++ - 如何保存对抽象基类的指针/引用但仍可在 C++ 中复制
- python - 在python中将字节转换为浮点数或字符串
- ruby-on-rails - Rails 如何处理具有异常复数的模型名称
- r - 将一列分类变量按顺序添加到数据框列表中
- ios - UItableview 单元格内的GrowingTextView 或可扩展文本视图
- android - 完成活动时的Android android.permission.INTERACT_ACROSS_USERS警告
- javascript - 使用 es6 使用动态键连接 setState
- javascript - c3.js如何将y标签放置在水平条形图中的条内?
- css - 为什么在调整窗口大小时输入字段的左侧没有空间?
- python - 在 PyQt 的文件夹中显示文件