【问题标题】:comparing a string at index i to a value in C++将索引 i 处的字符串与 C++ 中的值进行比较
【发布时间】: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");
}

【问题讨论】:

标签: c++ string string-comparison


【解决方案1】:

C++ 和许多其他语言的数组索引使用从零开始的索引。这意味着对于大小为 5 的数组,索引范围从 0 到 4。在您的代码中,您正在从 1 迭代到 array_length。采用: for (int i = 0; i &lt; binaryNumber.length(); i++)

【讨论】:

  • 谢谢!!我盯着这个看了很久。我故意从 i = 1 开始跳过第一个值,因为它始终为 0,并且不需要计算。出于某种原因,我放了
  • @PrometheusAurelius 第一个值不会是 0。以 1011(13) 为例。如果你反转它,它将是 1101。
  • 又一个脑屁,哈哈。感谢您指出了这一点。我的最后一个程序与这个程序相反,总是以 0 结尾(然后翻转后第一个数字为零),我必须纠正它。
【解决方案2】:

问题不在于 if 语句,而在于您的循环条件和索引。

您的索引从 1 开始,而字符串的第一个字符将从索引 0 开始。您的 out memory range 错误是由于循环在小于或等于时停止,导致索引增加太多并离开字符串的内存范围。

只需更改循环

for (int i = 1; i <= binaryNumber.length(); i++) {
    if(binaryNumber.at(i) == '0') {
    }
    else {
        adder = pow(2, i);
        total = adder + total;
    }
}

for (int i = 0; i < binaryNumber.length(); i++) {
    if(binaryNumber.at(i) == '0') { 
    }
    else {
        adder = pow(2, i);
        total = adder + total;
    }
}

将解决问题。

【讨论】:

    【解决方案3】:

    因为你是从 1 而不是 0 开始的

    for (int i = 1; i <= binaryNumber.length(); i++)
    

    试试看

    for (int i = 0; i < binaryNumber.length(); i++)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 2020-07-01
      • 2021-10-02
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多