二進(jìn)制轉(zhuǎn)十進(jìn)制:
- 以字符串的形式讀入二進(jìn)制串。
- 獲得該字符串的位數(shù),即二進(jìn)制的最高位是多少。
- 從左往右遍歷 == 從高位往低位展開!
- 核心:按權(quán)展開,按位相加。
代碼:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
string str;
int main()
{
getline(cin, str);
int n = str.size();
int sum=0;
for (int i=0; i < n; i ++)
{
int nums = str[i] - '0'; //字符數(shù)字轉(zhuǎn)化為int類型的數(shù)字
sum = sum + nums * pow(2, n-i-1);
}
cout << sum << endl;
return 0;
}
十進(jìn)制轉(zhuǎn)換為二進(jìn)制:
思路:
- 十進(jìn)制轉(zhuǎn)化為 x x x 進(jìn)制采用的是除 x x x 取余法(從下往上取余數(shù))。
- 所以說我們需要不斷模擬的是輾轉(zhuǎn)相除法,然后對于余數(shù)進(jìn)行存儲(chǔ),記住余數(shù)是不能相加求和的。要存儲(chǔ)下來!
代碼:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e2 + 10;
int a[N]; //存儲(chǔ)余數(shù)的!
int main()
{
int x;
cin >> x;
int idx=0;
while (x)
{
a[idx ++] = x % 2;
x/=2; //除以所要轉(zhuǎn)化的進(jìn)制的基數(shù)。
}
reverse(a, a+idx);
for (int i=0; i < idx; i ++)
cout << a[i];
return 0;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-529064.html
文章來源:http://www.zghlxwxcb.cn/news/detail-529064.html
到了這里,關(guān)于二進(jìn)制與十進(jìn)制的轉(zhuǎn)換【相互轉(zhuǎn)換, C++】的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!