繁体   English   中英

从Decimal转换为Base R c ++

[英]Converting from Decimal to Base R c++

在此先感谢您的帮助。

我得到了一个接受以下输入的作业:

init_base which is the base we are converting to. 2<=init_base and 36>= init_base
in_num which is the decimal number that is to be converted
in_num gets written to multiple times for each decimal number
the input is terminated with a -1

我被告知当数字大于9时使用字母表的大写字母。

我已经为解决方案编写了代码。 代码运行但我经常得到一个奇怪的输出。 我不确定为什么会这样。 我认为这与我的数据类型转换有关。 但是我不太确定会出现什么问题。

#include <iostream>
#include <cmath>
#include <string>
#include <stdlib.h>
#include <algorithm> 

using namespace std;
string ans;
int counter = 0;
bool Alpha_check(int val){
    if(val>9){
        return true;
    }
    else{
        return false;
    }
}
char Al_conv(int val){
    if(Alpha_check(val)){
        return char(val+55);
    }
    else {
         return char((val-48)+'0'); 
    }
}
void add_On(int c){
    ans.append(Al_conv(c));
    counter++;
}

int div_loop(int num, int base){    
    int temp = int(num/base);
    int temp2 = int(num%base);
    add_On(temp2);
    return temp;
}

void add_line(int number){
    ans[number] = '\n';
}

int main(){
    int init_base, in_num = 0;
    cin >> init_base;
    cin >> in_num;
    do{
        string rem;
        int init_count = counter;
        while(in_num!=0){
            in_num = div_loop(in_num,init_base);
        }
        int helper = int(floor((counter-init_count)/2));
        for(int y = 0; y < helper; y++){
            int temp = ans[y+init_count];
            ans[y+init_count] = ans[(counter-1)-y];
            ans[(counter-1)-y] = temp;
        }
        add_line(counter);
        counter++; 
        cin >> in_num;
    }while(in_num!=-1);
    ans[counter] = '\0';
    for(int gh = 0; gh < ans.length(); gh++){
        cout << ans[gh];
    }
    cout << endl;


     return 0;
}

这里还有一个链接供您关注http://ideone.com/qFOtyl以查看输出。

将问题分成两部分,解决方案很简单。 第一部分,使用base和modulo运算符分割数字中的输入数字。 然后,将它们转换为适合输出的字符。

///Given a maximum base of 36, the input of this function is in the range [0..35]
char toAlphaNumericSingleDigit(int input) {
    if (input < 10) {
         return '0' + input;
    } else {
         return 'A' + (input - 10);
    }
}

void print_conversion(int input, int base) {
    while (input > 0) {
         std::cout << toAlphaNumericSingleDigit(input % base);
         input /= base; ///Proceeds to the next digit
    }
    std::cout << std::endl;
}

请注意,这将以相反的顺序打印输出字符,从最不重要到最重要。

测试:

int main() {
    print_conversion(1294,36);
    return 0;
}

打印:

YZ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM