我正在尝试创建一个将二进制数(字符串)转换为十进制数(int)的函数 . 关于下面代码的奇怪部分是 when the line "//cout << index << endl;" is not commented out, it works! WHY D:?
注释掉时的输出:
1651929379
活动时输出:
7 192程序以退出代码结束:0
Here's the entire program:
//
// 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;
}
2 回答
您在
BinaryToDecimal
中有未定义的行为,因为变量solution
可能未初始化使用 .未初始化的局部变量将具有不确定的值(即它们的值看起来是随机的) .
正如Joachim所说,你的解决方案变量是未初始化的,所以当字符串既不是_464236也不是"1"时,你的=操作中可能会出现奇怪的行为(例如整数溢出) . 我想当输出有效时它工作的事实是由于输出指令的一些奇怪的副作用导致一些寄存器包含0,并且该寄存器是
solution
的值的来源 . 知道您的编译器设置是什么,并查看代码的这部分的汇编代码可能很有启发性 .你可以替换:
有:
由于您执行的特殊情况处理优先由您的循环处理 .