Algoritmo de cambio de base

Necesitaría un algoritmo en C que se pueda compliar con Borland C++ 4.5, que cambie de cualquier base a cualquier base un numero dado.

1 Respuesta

Respuesta
1
¿Cuándo te refieres a cualquier base, te refieres a las bases usuales? (Binario, octal, decimal, hexadecimal)
Las bases non usuales pueden ser complicadas de programar cuando base > 16. ¿El problema proviene del formalismo... Como representar una base 50? ¿Con letras? ¿Formas?
Especifica un poco mas y tratare ayudarte.
Ah vale, perdona :)  Lo que necesito es un programa que pida un número en la base que se desee, y que dé el resultado en la misma u otra base deseada. Sólo necesito las bases de 1 a 9.
Muchas gracias.
Aqui tienes la solucion a tu problema: solo te queda crear el main y poner los includes necesarios para que te compile Borland C++
string convert(int M, int N)
{
    //create a stream used for conversion
    std::stringstream out;
    //if M > N
    if (M < N)
    {
         //No need to continue: Create a new string with the result
         out << M;
         return string(out.str());
    }
    else
   {
        //Compute the modulo and convert it as string
        out << M % N;
       return convert(M/N, N) + string(out.str());
    }
}
extern "C"  int baseConverter(int number, int base, int newBase)
{
    //Convert the input number to string
    std::stringstream out;
    out << number;
    string s(out.str());
    //convert to base 10
    int conversion = 0;
    int power = s.length()-1;
    for ( unsigned int pos = 0; pos < s.length(); pos++)
    {
         char digit = s.at(pos);
        conversion += atoi(&digit)*(int)pow(base, power);
       power--;
    }
    //convert to the new base
    cout << "(" << number << ")" << base << " =" << " (" << convert(conversion, newBase) << ")" << newBase << endl;
    return 0;
}
Quita el extern "C" que hay delante del metodo baseConverter
Hola de nuevo Bebware, perdona por ser pesado :) He intentado varias veces hacer lo que me dijiste, pero no compila. Te dejo el código tal y como lo he intentado compilar, quizá he olvidado añadir o quitar algo.
#include <stdio.h>
#include <string.h>
int main (void)
{
string convert(int M, int N)
{
  //create a stream used for conversion
  std::stringstream out;
  //if M > N
  if (M < N)
  {
   //No need to continue: Create a new string with the result
   out << M;
   return string(out.str());
  }
  else
 {
    //Compute the modulo and convert it as string
    out << M % N;
   return convert(M/N, N) + string(out.str());
  }
}
baseConverter(int number, int base, int newBase)
{
  //Convert the input number to string
  std::stringstream out;
  out << number;
  string s(out.str());
  //convert to base 10
  int conversion = 0;
  int power = s.length()-1;
  for ( unsigned int pos = 0; pos < s.length(); pos++)
  {
   char digit = s.at(pos);
    conversion += atoi(&digit)*(int)pow(base, power);
   power--;
  }
  //convert to the new base
  cout << "(" << number << ")" << base << " =" << " (" << convert(conversion, newBase) << ")" << newBase << endl;
  return 0;
}
}
No utilizo Borland pero intentalo asi. Lo que te falta son includes... la proxima vez mandame los mensaje de error de compilacion...
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
string convert(int M, int N) 

  //create a stream used for conversion 
  std::stringstream out; 
  //if M > N 
  if (M < N) 
  { 
   //No need to continue: Create a new string with the result 
   out << M; 
   return string(out.str()); 
  } 
  else 
 { 
    //Compute the modulo and convert it as string 
    out << M % N; 
   return convert(M/N, N) + string(out.str()); 
  } 

int main( int argc, const char* argv[] )
{
int base;
int newBase;
int number;
// ensure the correct number of parameters are used.
if ( argc == 4 )
{
    number = atoi( argv[1] );
    base = atoi( argv[2] );
    newBase = atoi(argv[3]);
//Convert the input number to string 
  std::stringstream out; 
  out << number; 
  string s(out.str()); 
  //convert to base 10 
  int conversion = 0; 
  int power = s.length()-1; 
  for ( unsigned int pos = 0; pos < s.length(); pos++) 
  { 
   char digit = s.at(pos); 
    conversion += atoi(&digit)*(int)pow(base, power); 
   power--; 
  } 
  //convert to the new base 
  cout << "(" << number << ")" << base << " =" << " (" << convert(conversion, newBase) << ")" << newBase << endl;
}
}
Hola de nuevo Bebware. Perdona por tardar tanto. Aquí te dejo otra vez el código y sus errores como me dijiste. Los errores estan abajo del todo. He probado a corregirlos, pero no hay manera, a pesar de que parecen sencillos de solucionar. Bueno, muchas gracias.
#include <sstream.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
int main (void)
{
string convert(int M, int N)
{
  //create a stream used for conversion
  std::stringstream out;
  //if M > N
  if (M < N)
  {
 //No need to continue: Create a new string with the result
 out << M;
 return string(out.str());
  }
  else
 {
  //Compute the modulo and convert it as string
  out << M % N;
 return convert(M/N, N) + string(out.str());
  }
}
int main( int argc, const char* argv[] )
{
int base;
int newBase;
int number;
// ensure the correct number of parameters are used.
if ( argc == 4 )
{
  number = atoi( argv[1] );
  base = atoi( argv[2] );
  newBase = atoi(argv[3]);
//Convert the input number to string
  std::stringstream out;
  out << number;
  string s(out.str());
  //convert to base 10
  int conversion = 0;
  int power = s.length()-1;
  for ( unsigned int pos = 0; pos < s.length(); pos++)
  {
 char digit = s.at(pos);
  conversion += atoi(&digit)*(int)pow(base, power);
 power--;
  }
  //convert to the new base
  cout << "(" << number << ")" << base << " =" << " (" << convert(conversion, newBase) << ")" << newBase << endl;
}
}
}
Errores:
Compiling BASE.CPP:
Error BASE.CPP 1: Unable to open include file 'SSTREAM.H'
Error BASE.CPP 7: Undefined symbol 'string' in function main()
Error BASE.CPP 7: Statement missing ; in function main()
Error BASE.CPP 54: Compound statement missing } in function main()
Warning BASE.CPP 54: Function should return a value in function main()
Tienes dos metodos main...
Eso no tiene nada que ver con lo que te pase en mi anterior mensaje... vuleve a copiar correctamente y pasame los mensajes de error si hay.
Te prometo que este codigo va perfectamente con 99% de loscompilador existentes...
Cuanto al error de sstream... puede que borland no lo tenga...
Suerte

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas