【发布时间】:2021-09-18 01:13:25
【问题描述】:
所以我正在做一个班级作业,我需要取一个以 2 为底的二进制数并将其转换为以 10 为底的等效值。我想将二进制存储为字符串,然后扫描字符串并跳过 0,并在 1 处添加 2^i。我无法将索引 i 处的字符串与 '0 进行比较,我不确定为什么 if(binaryNumber.at(i) == '0') 不起作用。它会导致“超出范围的内存错误”。有人可以帮我理解为什么这不起作用吗?
#include <iostream>
using namespace std;
void main() {
string binaryNumber;
int adder;
int total = 0;
cout << "Enter a binary number to convert to decimal \n";
cin >> binaryNumber;
reverse(binaryNumber.begin(),binaryNumber.end());
for (int i = 1; i <= binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') { //THIS IS THE PROBLEM
//do nothing and skip to next number
}
else {
adder = pow(2, i);
total = adder + total;
}
}
cout << "The binary number " << binaryNumber << " is " << total << " in decimal form.\n";
system("pause");
}
【问题讨论】:
-
是什么原因?我通常这样做,但我的老师提供了骨架 main() 函数,它是无效的。
-
它不是有效的 C++,所以一些编译器可能会出错。 See example.
标签: c++ string string-comparison