c++二进制转十进制
?代碼
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
double power(double x, int n); // 原函數(shù)聲明
int main () ?{
?? ?__int64 value;//二進(jìn)制64位?
?? ?char c[64];
?? ?
?? ?while (cin >> c){
?? ??? ?if(c[0] == '-'){
?? ??? ??? ?break;
?? ??? ?}
?? ??? ?int len = strlen(c); ?// 獲取輸入的二進(jìn)制的長(zhǎng)度strlen() 函數(shù)從字符串的開(kāi)頭位置依次向后計(jì)數(shù),直到遇見(jiàn)\0,然后返回計(jì)時(shí)器的值。最終統(tǒng)計(jì)的字符串長(zhǎng)度不包括\0
?? ??? ?value = 0;
?? ??? ?for (int i = len - 1; i >= 0; i--){
?? ??? ??? ?if (c[i] == '1'){
//?? ??? ??? ??? ?2的i次方結(jié)果為double類型,轉(zhuǎn)換為int類型,然后累加到value上。
?? ??? ??? ??? ?value += static_cast<__int64>(power(2, len - i - 1)); // static_cast<__int64>(參數(shù))將double型數(shù)據(jù)轉(zhuǎn)換成__int64型數(shù)據(jù)
?? ??? ??? ?}
?? ??? ?}
?? ??? ?cout ?<< value << endl;
?? ?}?
}
double power (double x, int n){ ?// 返回給定數(shù)字的乘冪,返回類型為double型
?? ?double val = 1.0;
?? ?
?? ?while (n--){
?? ??? ?val *= x;?? ?
?? ?}?
?? ?return val;
}
?
總結(jié)
以上是生活随笔為你收集整理的c++二进制转十进制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 波士顿房价预测模型源代码
- 下一篇: C++运用类函数创造对象,求自定义边长的