# c++二进制转十进制_日积月累：C++实现十进制与二进制之间的互相转换

1、十进制转换二进制

(十进制转换二进制示意图)

#include#include#include#include#includeusing namespace std;void convert_10_to_2(int num){    vector<int> ivec;    int Num = num;  //存储原数据    //对原数据循环求除以2的余数,并存储在vector对象中    while (num != 0)    {        ivec.push_back(num % 2);        num = num / 2;    }     //对求得的余数倒序排序并存储在vector中，求得二进制    vector<int>::size_type sz = ivec.size();    vector<int> ivec2;    for (vector<int>::size_type index = 0; index != sz; ++index)        ivec2.push_back(ivec[sz - 1 - index]);     //输出十进制转换为二进制的数    cout <"十进制转二进制后为：";    for (auto item : ivec2)        cout << item;    cout << endl<<endl;}

#include#include#include#include#includeusing namespace std;int main(){        int N;    cout << "Please enter the number: ";    cin >> N;    cout << endl;     //十进制转二进制的声明和调用    void  convert_10_to_2(int num);    convert_10_to_2(N);}

2、二进制转换十进制

(二进制转换十进制示意图)

#include#include#include#includeusing namespace std;double convert_2_to_10(){    //输入二进制数并存储在vector变量ivec2中    cout << "Please enter the ErJInZhi numbers:  " << endl;    int n;    vector<int> ivec2;    while (cin >> n)    {        ivec2.push_back(n);    }     //二进制转十进制计算    double sum = 0, times;    vector<int>::size_type sz = ivec2.size();    for (vector<int>::size_type index = 0; index != sz; ++index)    {        times = pow(2, sz - 1 - index);        sum += ivec2[index] * times;    }     //输出转化后的结果    cout << "2进制——";    for (vector<int>::size_type index = 0; index != sz; ++index)        cout << ivec2[index];    cout << "转10进制为：";    cout << sum << endl;    return 0;}

#include#include#include#include#includeusing namespace std;int main(){    double convert_2_to_10();    convert_2_to_10();    return 0;}

(输入二进制时要以空格区分)

~关于涵爸的介绍

8年奶爸生涯刚结束

• 0
点赞
• 0
收藏
• 0
评论
01-22
11-28 5
10-05 1640
09-26 1025
08-06 1万+
07-09 8030
04-10 3757
02-09 1930
11-01 506
07-09 2402

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助