Блог пользователя mohelli5

Автор mohelli5, 11 лет назад, По-английски

hi , i have a little problem in chaniging the base of a number from ten to 4 if someone here can write the code it will be helpful in qbasic or c++ plz thanks

  • Проголосовать: нравится
  • -8
  • Проголосовать: не нравится

»
11 лет назад, # |
Rev. 5   Проголосовать: нравится +3 Проголосовать: не нравится

The algorithm of converting a decimal number to any base is quite easy. suppose the number is N and the desired base is B ,then algorithm goes like this: We take an array to keep the remainder and also to print result and we also take a variable 'index' to fix the index in the array ==>

arr[100010],index=0;
while  N does not become zero -> 
[
1.ara[index++]=N%B
2. N=N/B
]
Reverse the array and print it.
Or print the array from last to start.

<== Here is my code: -------------------->

#include<stdio.h>
#include<iostream>
using namespace std;
int ara[10010],index=0;
int main()
{
    int N,B;
    cin>>N>>B;
    while(N!=0)
    {
        ara[index++]=N%B;
        N=N/B;
    }
    for(int i=index-1;i>=0;i--) cout<<ara[i];
    cout<<endl;
}

<---------------------------- You can use itoa function to do it faster but remember it is not supported by GNU compiler. But what the hell??! You can though use it to debug any code very fast. Here is a reference to itoa function http://www.cplusplus.com/reference/cstdlib/itoa/ :) :)