【问题标题】:Super weird error when handling strings处理字符串时出现超级奇怪的错误
【发布时间】:2014-03-14 03:29:10
【问题描述】:

我正在尝试创建一个将二进制数(字符串)转换为十进制数(int)的函数。下面代码的奇怪之处在于 当行“//cout

注释掉时的输出:

1651929379

激活时输出:

7 192 程序以退出代码结束:0

这是整个程序:

//
//  testish.cpp
//  Egetskojs
//
//  Created by Axel Kennedal on 2014-02-13.
//  Copyright (c) 2014 Axel Kennedal. All rights reserved.
//

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int BinaryToDecimal(string & binaryString);

int main(){

    string binary = "11000000";
    int decimal = BinaryToDecimal(binary);
    cout << decimal << endl;




    return 0;
}


int BinaryToDecimal(string & binaryString){
    int solution;

    if (binaryString == "0") solution = 0;
    if (binaryString == "1") solution = 1;

    int index = binaryString.length() - 1; //The index of the last (rightmost) bit in the string
    //cout << index << endl;

    int currentBit = 0; //The exponent to be used when calculating the value of a bit

    for (; index >= 0; index--) {
        if (binaryString.at(index) == '1') {
            solution += pow(2, currentBit);
        }
        //Else: nothing happens
        currentBit++;
    }

    //Done!
    return solution;
}

【问题讨论】:

    标签: c++ string function binary syntax-error


    【解决方案1】:

    BinaryToDecimal 中有未定义的行为,因为变量 solution 可能未初始化使用。

    未初始化的局部变量将具有不确定的值(即它们的值看起来是随机的)。

    【讨论】:

    • 好的,谢谢:)!但是当我使用那个 cout 时它是怎么工作的呢?
    【解决方案2】:

    正如 Joachim 所说,您的解决方案变量未初始化,因此当字符串既不是“0”也不是“1”时,您的 += 操作可能会出现奇怪的行为(例如整数溢出)。我猜想它在输出处于活动状态时起作用的事实是由于输出指令的一些奇怪的副作用导致某些寄存器包含 0,并且该寄存器是 solution 值的来源。了解您的编译器设置是什么,并查看这部分代码的汇编代码可能会很有启发性。
    您可以替换:

    int BinaryToDecimal(string & binaryString){
        int solution;
    
        if (binaryString == "0") solution = 0;
        if (binaryString == "1") solution = 1;
        ...
    

    与:

    int BinaryToDecimal(string & binaryString){
        int solution = 0;
        ...
    

    由于您所做的特殊情况处理由您的循环优雅地处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 2010-12-29
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2015-11-22
      相关资源
      最近更新 更多