`
RednaxelaFX
  • 浏览: 3048148 次
  • 性别: Icon_minigender_1
  • 来自: 海外
社区版块
存档分类
最新评论

某人的作业,A档第五题

阅读更多
题目:
引用
五、 进制转换器(10)
   要求:(1)可输入二进制、八进制、十进制、十六进制数;
        (2)将已输入的数转换成其余进制的数;
        (3)具有输入输出界面。


简单解答:
#include <cstdlib>
#include <iostream>

using namespace std;

string toBinaryString(int num) {
    char buffer[33];
    memset(buffer, 0, 33);
    itoa(num, buffer, 2);
    string result(buffer);
    return result;
}

int fromBinaryString(string& in) {
    int length = in.length();
    int result = 0;
    for (int i = 0; i < length; ++i)
        if ('1' == in[i])
            result |= 1 << (length - i - 1);
    return result;
}

void printNumber(int num) {
    cout << "binary: " << toBinaryString(num) << endl;
    cout << "octal: " << oct << num << endl;
    cout << "decimal: " << dec << num << endl;
    cout << "hexadecimal: " << hex << num << dec << endl;
}

void promptRadix() {
    cout << "Enter a decimal number as radix (2, 8, 10, 16): ";
}

void promptNumber() {
    cout << "Enter a number in the above radix: ";
}

int main () {
    string input;
    int radix;
    int num;
    
    promptRadix();
    getline(cin, input);
    radix = atoi(input.c_str());
    
    switch (radix) {
    case 2:
        promptNumber();
        getline(cin, input);
        num = fromBinaryString(input);
        printNumber(num);
        break;
    case 8:
        promptNumber();
        cin >> oct >> num;
        printNumber(num);
        break;
    case 10:
        promptNumber();
        cin >> dec >> num;
        printNumber(num);
        break;
    case 16:
        promptNumber();
        cin >> hex >> num;
        printNumber(num);
        break;
    default:
        cout << "invalid radix." << endl;
        break;
    }
    
    return 0;
}


这次更懒了……干脆不检查了 = -
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics