Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 10 years ago

# 2進位轉換成10進位的程式要怎麼寫

2進位轉換成10進位的程式要怎麼寫

int convert(String ninaryNumber)

Rating
• 10 years ago

// C++ Language

#include <iostream>

#include <string>

#include <cmath>

using namespace std;

int convert(string);

int isBinary(string);

void main() {

int decimalNumber;

string myBinaryStr;

do {

cout << "Enter a binary number: ";

getline(cin, myBinaryStr);

} while (!isBinary(myBinaryStr));

decimalNumber = convert(myBinaryStr);

cout << "Result: " << decimalNumber << endl;

}

int convert(string binaryNumber)

{

int decimal=0, placeValue;

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

placeValue = binaryNumber.size() - 1 - i;

if (binaryNumber[i]=='1')

decimal += (int)pow(2.0, (double)placeValue);

}

return decimal;

}

int isBinary(string binaryNumber)

{

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

if (!(binaryNumber[i]=='1'||binaryNumber[i]=='0'))

return 0;

}

return 1;

}

Source(s): 自己
• 其威
Lv 7
10 years ago

請提供 String 的 class 定義或 typedef 與 struct 定義, 否則沒辦法做.