【发布时间】: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