#include <iostream>
#include <string>
using namespace std;

void decToR(int x, int R) {
    if (x == 0) { // 特判
        cout << "0" << endl;
        return;
    }
    string res = "";
    while (x) {
        int t = x % R;
        if (t < 10) res = to_string(t) + res;
        else res = char(t - 10 + 'A') + res;
        x /= R;
    }
    cout << res << endl;
}

int main() {
    int x, R;
    while (true) {
        cout << "请输入十进制数x和进制R(2<=R<=16): ";
        cin >> x >> R;
        if (x < 0 || R < 2 || R > 16) {
            cout << "输入不合法,请重新输入!" << endl;
            continue;
        }
        if (x == 0) break; // 输入为 0,退出循环
        decToR(x, R);
    }
    return 0;
}
用C++编写函数该函数能完成任意的十进制数x转换为R2≤R≤16进制数。调用该函数将输入的一个十进制正整数分别转换为R进制数数字串。要求:1在主函数中需要用循环完成多次转换输入的x或R为负数时应提示重新输入;输入的十进制数为0时停止转换。 2在主函数中输出转换结果。 3测试结果应该能够反映R=2、R=8、R=16和x=0的情况。

原文地址: https://www.cveoy.top/t/topic/bYUy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录