Vous êtes sur la page 1sur 13

Cátedra de Informática Electrónica

Escuela de Ingeniería Electrónica


Dpto. de Sistemas e Informática

Practica 4: Programación en C++

Parte A

1) Un número entero de n dígitos se dice que es narcisista si se puede obtener como la suma de las
potencias
n-ésimas de cada uno de sus dígitos. Por ejemplo 153 y 8208 son números narcisistas porque 153 =
13 + 53 + 33
y 8208 = 84 + 24 + 04 + 84. Construir una función que, dado un número entero positivo, devuelva un
valor que
indique si el número es o no narcisista.

2) Las funciones trigonométricas (sin(), cos() y tan()) de la biblioteca estándar <cmath>


toman sus argumentos en radianes. Escribir en C++ tres funciones equivalentes, llamadas
singrad(), cosgrad() y tangrad() que tomen sus argumentos en grados. Todos los
argumentos y valores de retorno deblen ser de tipo double.

3) Escribir una familia de funciones sobrecargadas llamadas equal(), que tomen dos argumentos
del mismo tipo y retornen 1 si los argumentos son iguales y 0 si no. Proveer versiones con
argumentos de tipo char, int, double y char* (Usar la función strcpm() de la biblioteca
para testear igualdad de strings. Se necesita #include <csstring>). Escribir código para
testear que son invocadas las versiones corerspondientes.

4) Se tiene un vector cargado con los apellidos de N alumnos. Escribir un programa que solicite el
apellido de un alumno por teclado y verifique si se encuentra en el vector.

5) Definir una clase para representar una pila de enteros. Una pila es una lista de items que permite
agregar (push) o sacar (pop) sólo de un extremo, operando con el principio LIFO (last-in, first out).
Por ejemplo, si la pila contiene [10 4 16 20], pop() debe retornar 10, y luego la pila queda
[4 16 20]. Un subsecuente push(13) debe dejar la pila en [13 4 16 20]. No se puede
obtener un item que no esté en el top, salvo que se quiten todos los items que están sobre él. La
clase debe implementar las funciones push(), pop() y una función print() para mostrar el
estado de la pila. Guardar la lista internamente como un arreglo. Escribir un programa de test para
verificar el correcto funcionamiento de la clase.

6) a- Implementar una clase CSimpleString que contenga un char* y un entero (longitud)


como campos miembro privados. Proveer un constructor que tome un argumento de tipo const
char*. Implementar además las funciones constructor de copia, destructor y sobrecarga del
operador de asignación. Verificar que la clase funciona. Ayuda: Utilizar funciones del archivo de
cabecera <cstring>.
b- ¿Qué otros constructores se pueden definir para la clase CSimpleString? Codificarlos.

7) Sobrecargar los operadores + y += para la clase del ejercicio anterior para concatenar strings.
8) Modificar la clase pila del ejercicio 5 de forma que el tamaño de la misma sea especificado
mediante un constructor con reserva de memoria. Agregar lo que sea necesario. Probar el
funcionamiento.

9) Dada la siguiente clase:

class CBase {
protected:
int m_anInt;
public:
CBase(int n) : m_anInt(n) { cout << "Base
constructor" << endl; }
virtual void Print() = 0;
};

¿Qué tipo de clase es y por qué? Derivar una clase de CBase que setee el valor de su entero
heredado m_anInt en el constructor y que lo imprima cuando sea requerido. Escribir un
programa de testeo para verificar que la clase es correcta.

10) Definir la clase Botella con campos miembro privados altura y diámetro. Luego, definir en otro
archivo la clase CajonBotellas con campos miembro alto, ancho y largo. El constructor de la clase
CajonBotellas toma una botella como argumento y debe poder acceder a sus campos para inicializar
sus atributos de forma que entren seis botellas en un cajón.

11) Una estación meteorológica se registra diariamente la temperatura máxima y mínima de todo un
año. Preparar un algoritmo para generar un archivo que contenga dichos datos (generados
aleatoriamente).

12) Imprimir en pantalla la máxima y la mínima temperatura anual. Extraer los datos del archivo
generado en el item anterior. Manejar excepciones.

Informática Electrónica – Práctica 4 – v. 2009 Pág 2 de 13


Parte B

13) Diseñar la clase Complejo. Instaciar un arreglo de cuatro complejos e inicializarlos


aleatoriamente. Asociar un led a cada cuadrante del plano complejo. Definir una función que al
activar el i-ésimo pulsador encienda el led correspondiente al cuadrante del i-ésimo complejo.

II I

III IV

14) Escribir un programa con una clase ArregloBinario cuyo campo miembro sea un arreglo
compuesto de ceros y unos cuya longitud coincida con la cantidad de leds de la placa. Proveer un
método inicio() para inicializarlo y otro método mapeo() para encender los leds
correspondientes de acuerdo a los valores del arreglo. Diseñar en la clase un método reverse()
que invierta el orden del arreglo (Por ejemplo: 10100111 -> 11100101). Testear los métodos en una
placa, de manera que reverse() se ejecute al accionar un pulsador.

Soluciones propuestas

Solución ejercicio 2:

#include <iostream>
#include <cmath>
using std::cout;
using std::endl;
using std::sin;
using std::cos;
using std::tan;

const double DEG_TO_RAD = 57.2957795;

double sind(double d)
{
return sin(d/DEG_TO_RAD);
}

double cosd(double d)
{
return cos(d/DEG_TO_RAD);
}

double tand(double d)
{
return tan(d/DEG_TO_RAD);
}

int main()
{
cout << "cos(30) = " << cosd(30.0) << endl;
cout << "sin(30) = " << sind(30.0) << endl;
cout << "tan(30) = " << tand(30.0) << endl;

Informática Electrónica – Práctica 4 – v. 2009 Pág 3 de 13


return 0;
}

Solución ejercicio 3:

#include <iostream>
#include <cstring>
using std::cin;
using std::cout;
using std::endl;

int equal(int a,int b)


{
return (a==b) ? 1 : 0;
}

int equal(double a,double b)


{
return (a==b) ? 1 : 0;
}

int equal(char a,char b)


{
return (a==b) ? 1 : 0;
}

int equal(char* a,char* b)


{
return strcmp(a,b)==0 ? 1 : 0;
}

int main()
{
int iA=3, iB=5;
cout << "Comparing iA = " << iA << " and iB = " << iB << endl;
if (equal(iA,iB))
cout << "iA and iB are the same" << endl;
else
cout << "iA and iB are different" << endl;

double dA=3.5, dB=3.5;


cout << "Comparing dA = " << dA << " and dB = " << dB << endl;
if (equal(dA,dB))
cout << "dA and dB are the same" << endl;
else
cout << "dA and dB are different" << endl;

char* pA = "hello";
char* pB = "mickey";
cout << "Comparing pA = \"" << pA << "\" and pB = \"" << pB << "\"" << endl;
if (equal(pA,pB))
cout << "pA and pB are the same" << endl;
else
cout << "pA and pB are different" << endl;

char* pC = "mickey";
cout << "Comparing pB = \"" << pB << "\" and pC = \"" << pC << "\"" << endl;
if (equal(pB,pC))
cout << "pB and pC are the same" << endl;
else
cout << "pB and pC are different" << endl;

Informática Electrónica – Práctica 4 – v. 2009 Pág 4 de 13


return 0;
}

Solución ejercicio 5:
#include <iostream>

using std::cout;
using std::endl;

class CStack
{
public:
CStack() : next(0) {}
void push(int i);
int pop();
void print();
private:
int list[100];
int next;
};

// Push a value on to the stack


void CStack::push(int i)
{
if (next < 99)
list[next++] = i;
}

// Pop a value off the stack


int CStack::pop()
{
return list[--next];
}

// Output the contents of the stack


void CStack::print()
{
cout << '[';
for(int i=next-1 ; i>=0 ; i--)
cout << ' '<< list[i];
cout << " ]\n";
}

int main()
{
CStack s;

s.print();

s.push(5);

s.push(10);
s.push(8);

s.print();

cout << "top of stack=" << s.pop() << endl;

s.print();

Informática Electrónica – Práctica 4 – v. 2009 Pág 5 de 13


return 0;
}

Solución ejercicio 6 - a:

#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

class CSimpleString
{
private:
size_t len;
char* buff;
public:
CSimpleString(const char* p = 0);
CSimpleString(const CSimpleString& s);
~CSimpleString();

CSimpleString& operator=(const CSimpleString& rhs);


void print();
};

// Constructor
CSimpleString::CSimpleString(const char* p) : len(0), buff(0)
{
if (p != 0)
{
len = strlen(p);
if (len > 0)
{
buff = new char[len+1];
strcpy_s(buff, len+1, p);
}
}
}

// Copy constructor
CSimpleString::CSimpleString(const CSimpleString& s)
{
len = s.len;
buff = new char[len+1];
strcpy_s(buff, len+1, s.buff);
}

// Destructor
CSimpleString::~CSimpleString()
{
delete buff;
}

// Assignment operator - does not deal with str = str


CSimpleString& CSimpleString::operator=(const CSimpleString& rhs)
{
len = rhs.len;
delete buff;
buff = new char[len+1];
strcpy_s(buff, len+1, rhs.buff);

return *this;

Informática Electrónica – Práctica 4 – v. 2009 Pág 6 de 13


}

void CSimpleString::print()
{
cout << buff;
}

int main()
{
CSimpleString s1 = "hello";
CSimpleString s2 = "goodbye";
cout << "s1: \"";
s1.print();
cout << "\"" << endl;

cout << "s2: \"";


s2.print();
cout << "\"" << endl;

cout << " After executing s2 = s1:" << endl;


s2 = s1;

cout << "s1 = \"";


s1.print();
cout << "\"" << endl;

cout << "s2 = \"";


s2.print();
cout << "\"" << endl;

return 0;
}

Solución ejercicio 6 - b:
#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

class CSimpleString
{
private:
size_t len;
char* buff;
public:
CSimpleString(const char* p = 0);
CSimpleString(const CSimpleString& s);

CSimpleString(char c, int count=1);


CSimpleString(int i);

~CSimpleString();

CSimpleString& operator=(const CSimpleString& rhs);


void print();
};

// Contructor - repeated given character


CSimpleString::CSimpleString(char c, int count) : len(0), buff(0)

Informática Electrónica – Práctica 4 – v. 2009 Pág 7 de 13


{
len = count;
if (len > 0)
{
buff = new char[len+1];
memset(buff, c, len);
buff[len] = '\0';
}
}

// Constructor - from an integer


CSimpleString::CSimpleString(int i) : len(0), buff(0)
{
char sTmp[20];
_itoa_s(i, sTmp, 20, 10);

len = strlen(sTmp);
if (len > 0)
{
buff = new char[len+1];
strcpy_s(buff, len+1, sTmp);
}
}

// Constructor
CSimpleString::CSimpleString(const char* p) : len(0), buff(0)
{
if (p != 0)
{
len = strlen(p);
if (len > 0)
{
buff = new char[len+1];
strcpy_s(buff, len+1, p);
}
}
}

// Copy constructor
CSimpleString::CSimpleString(const CSimpleString& s)
{
len = s.len;
buff = new char[len+1];
strcpy_s(buff, len+1, s.buff);
}

// Destructor
CSimpleString::~CSimpleString()
{
delete buff;
}

// Assignment operator - does not deal with str = str


CSimpleString& CSimpleString::operator=(const CSimpleString& rhs)
{
len = rhs.len;
delete buff;
buff = new char[len+1];
strcpy_s(buff, len+1, rhs.buff);

return *this;
}

Informática Electrónica – Práctica 4 – v. 2009 Pág 8 de 13


void CSimpleString::print()
{
cout << buff;
}

int main()
{
CSimpleString s1 = "hello";
CSimpleString s2;

s2 = s1;
CSimpleString marker = CSimpleString('*', 30);
marker.print();
cout << endl;

cout << "s1 = \"";


s1.print();

cout << "\"" << endl;

cout << "s2 = \"";


s2.print();
cout << "\"" << endl;

int n = 7890;

CSimpleString nStr = CSimpleString(n);

cout << n << " as a string is \"";


nStr.print();
cout << "\"" << endl;

marker.print();
cout << endl;
return 0;
}

Solución ejercicio 7:
#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

class CSimpleString
{
private:
size_t len;
char* buff;
public:
CSimpleString(const char* p = 0);
CSimpleString(const CSimpleString& s);
CSimpleString(char c, int count=1);
CSimpleString(int i);
~CSimpleString();

CSimpleString& operator=(const CSimpleString& rhs);


CSimpleString& operator+=(const CSimpleString& rhs);
CSimpleString operator+(const CSimpleString& s);
CSimpleString operator+(const char* s);
void print();

Informática Electrónica – Práctica 4 – v. 2009 Pág 9 de 13


};

CSimpleString::CSimpleString(char c, int count) : len(0), buff(0)


{
len = count;
if (len > 0)
{
buff = new char[len+1];
memset(buff, c, len);
buff[len] = '\0';
}
}

CSimpleString::CSimpleString(int i) : len(0), buff(0)


{
char sTmp[20];
_itoa_s(i, sTmp, 20, 10);

len = strlen(sTmp);
if (len > 0)
{
buff = new char[len+1];
strcpy_s(buff, len+1, sTmp);
}
}

CSimpleString::CSimpleString(const char* p) : len(0), buff(0)


{
if (p != 0)
{
len = strlen(p);
if (len > 0)
{
buff = new char[len+1];
strcpy_s(buff, len+1, p);
}
}
}

CSimpleString::CSimpleString(const CSimpleString& s)
{
len = s.len;
buff = new char[len+1];
strcpy_s(buff, len+1, s.buff);
}

CSimpleString::~CSimpleString()
{
delete buff;
}

// Assignment operator - does deal with str = str


CSimpleString& CSimpleString::operator=(const CSimpleString& rhs)
{
if (&rhs != this)
{
len = rhs.len;
delete buff;
buff = new char[len+1];
strcpy_s(buff, len+1, rhs.buff);
}

return *this;

Informática Electrónica – Práctica 4 – v. 2009 Pág 10 de 13


}

// Addition operator: add two CSimpleString objects


CSimpleString CSimpleString::operator+(const CSimpleString& s)
{
size_t length = len + s.len + 1;
char* tmp = new char[length];
strcpy_s(tmp, length, buff);
strcat_s(tmp, length, s.buff);

return CSimpleString(tmp);
}

// Addition operator: CSimpleString object + string constant


CSimpleString CSimpleString::operator+(const char* s)
{
return *this + CSimpleString(s);
}

// += operator
CSimpleString& CSimpleString::operator+=(const CSimpleString& rhs)
{
*this = *this + rhs;
return *this;
}

void CSimpleString::print()
{
cout << buff;
}

int main()
{
CSimpleString s1 = "hello";
CSimpleString s2;

s2 = s1;
CSimpleString marker = CSimpleString('*', 30);
marker.print();
cout << endl;

cout << "s1 = \"";


s1.print();

cout << "\"" << endl;

cout << "s2 = \"";


s2.print();
cout << "\"" << endl;

int n = 7890;

CSimpleString nStr = CSimpleString(n);

cout << n << " as a string is \"";


nStr.print();
cout << "\"" << endl;

CSimpleString* pStr = &s2;

s2 = *pStr; // s2 = s2
cout << "s2 = \"";
s2.print();

Informática Electrónica – Práctica 4 – v. 2009 Pág 11 de 13


cout << "\"" << endl;

s1 += " world!";

cout << "s1 = \"";


s1.print();

cout << "\"" << endl;

marker.print();
cout << endl;
return 0;
}

Solución ejercicio 8:
#include <iostream>
using std::cout;
using std::endl;

class CStack
{
public:
CStack(int n = 10);
~CStack();
void push(int i);
int pop();
void print();

private:
int* pList;
int size;
int next;
};

CStack::CStack(int n) : next(0), size(n)


{
pList = new int[size];
}

CStack::~CStack()
{
delete [] pList;
}

void CStack::push(int i)
{
if (next < 99)
pList[next++] = i;
}

int CStack::pop()
{
return pList[--next];
}

void CStack::print()
{
cout << '[';
for(int i=next-1 ; i>=0 ; i--)
cout << ' '<< pList[i];

Informática Electrónica – Práctica 4 – v. 2009 Pág 12 de 13


cout << " ]\n";
}

int main()
{
CStack s(20);

s.print();

s.push(5);
s.push(10);
s.push(8);

s.print();

cout << "top of stack=" << s.pop() << endl;

s.print();

return 0;
}

Solución ejercicio 9:
/*
CBase es una clase abstracta porque contiene la función virtual pura Print().
*/
#include <iostream>
using std::cout;
using std::endl;

class CBase
{
protected:
int m_anInt;
public:
CBase(int n) : m_anInt(n) { cout << "Base constructor" << endl; }
virtual void Print() = 0;
};

class CDerived : public CBase


{
public:
CDerived(int n) : CBase(n) { cout << "Derived constructor" << endl; }
void Print() { cout << "value is " << m_anInt << endl; }
};

int main()
{
CDerived d(3);

d.Print();

return 0;
}

Informática Electrónica – Práctica 4 – v. 2009 Pág 13 de 13

Vous aimerez peut-être aussi