0% found this document useful (0 votes)
59 views19 pages

Resolução de Exercícios EDA: 1-Data Types. Arithmetic Expressions. Input and Output

This document contains C++ code examples for solving various math and logic problems. The examples are grouped into sections covering data types, arithmetic expressions, control structures like if/else statements, and trigonometric functions. Each code sample accepts user input, performs calculations, and outputs results to demonstrate solutions to problems like calculating ASCII values, averages, sphere mass, linear systems, time addition, triangle properties, and determining prime numbers.

Uploaded by

InêsFontes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views19 pages

Resolução de Exercícios EDA: 1-Data Types. Arithmetic Expressions. Input and Output

This document contains C++ code examples for solving various math and logic problems. The examples are grouped into sections covering data types, arithmetic expressions, control structures like if/else statements, and trigonometric functions. Each code sample accepts user input, performs calculations, and outputs results to demonstrate solutions to problems like calculating ASCII values, averages, sphere mass, linear systems, time addition, triangle properties, and determining prime numbers.

Uploaded by

InêsFontes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

RESOLUÇÃO DE EXERCÍCIOS

EDA
1- DATA TYPES. ARITHMETIC EXPRESSIONS. INPUT AND
OUTPUT
1.1 LER UMA LETRA E RETORNAR O CÓDIGO ASCII

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

int main()
{
char c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII value of " << c << " is " << int(c);
return 0;
}

1.2 MÉDIA E DIFERENÇA ENTRE 3 NÚMEROS

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

int main()
{
double A, B, C;
double average, A_average, B_average, C_average;

cout << "Please, input 3 integer numbers"<<'\n';


cout << "A ? "; cin >> A;
cout << "B ? "; cin >> B;
cout << "C ? "; cin >> C;

average = (A + B + C) / 3;
A_average = A - average;
B_average = B - average;
C_average = C - average;

cout << "average = " << average << '\n';


cout << "A-average = " << A_average << '\n';
cout << "B-average = " << B_average << '\n';
cout << "C-average = " << C_average << '\n';
return 0;
}
1.3 MASSA DE UMA ESFERA E USAR  COMO CONSTANTE

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
const double PI = 3.1415;
double ro, r, M;

cout << "Specific mass(ro) in kg/m^3? "; cin >> ro;


cout << "Spere's radius(r) in m? "; cin >> r;

M = (4 * ro*PI*pow(r, 3))/3;

cout << "M=" << M<<" Kg";


return 0;
}

1.4 SOLUÇÃO DE UM SISTEMA DE EQUAÇÕES LINEARES

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double a, b, c, d, e, f, x, y;

cout << "a= "; cin >> a;


cout << "b= "; cin >> b;
cout << "c= "; cin >> c;
cout << "d= "; cin >> d;
cout << "e= "; cin >> e;
cout << "f= "; cin >> f;

x = (c*e - b * f) / (a*e - b * d);


y = (a*f - c * d) / (a*e - b * d);

cout << "x= "; cin >> x;


cout << "y= "; cin >> y;
return 0;
}
1.5 SOMAR TEMPOS

A) SOMAR 2 TEMPOS

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
int d1, d2, h1, h2, m1, m2, s1, s2, d, h, m, s;
cout << "Time1 (hours minutes seconds) ? "; cin >> h1 >> m1
>> s1;
cout << "Time2 (hours minutes seconds) ? "; cin >> h2 >> m2
>> s2;

s = (s1 + s2) % 60;


m = ((s1 + s2) / 60) + ((m2 + m1) % 60);
h = ((m1 + m2) / 60) + ((h2 + h1) % 24);
d = (h1 + h2) / 24;

cout << "Time1 + Time2 = " << d << " day, " << h << "
hours, " << m << " minutes and " << s << " seconds";
return 0;
}

B) CONSIDERAR QUE QUALQUER SEPARADOR É VÁLIDO

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int d1, d2, h1, h2, m1, m2, s1, s2, d, h, m, s;
char c1, c2, c3, c4;
cout << "Time1 (hours minutes seconds) ? "; cin >> h1
>>c1>> m1 >>c2>> s1;
cout << "Time2 (hours minutes seconds) ? "; cin >> h2
>>c3>> m2 >>c4>> s2;

s = (s1 + s2) % 60;


m = ((s1 + s2) / 60) + ((m2 + m1) % 60);
h = ((m1 + m2) / 60) + ((h2 + h1) % 24);
d = (h1 + h2) / 24;
cout << "Time1 + Time2 = " << d << " day, " << h << "
hours, " << m << " minutes and " << s << " seconds";
return 0;
}

1.6 ÁREA DE UM TRIÂNGULO

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
float s, area, x1, y1, x2, y2, x3, y3, a, b, c, p;

cout << "Please insert triangle coordinates" << '\n';


cout << "Vertice 1= "; cin >> x1 >> y1;
cout << "Vertice 2= "; cin >> x2 >> y2;
cout << "Vertice 3= "; cin >> x3 >> y3;

a = sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2));


b = sqrt(pow((x3 - x2), 2) + pow((y3 - y2), 2));
c = sqrt(pow((x1 - x3), 2) + pow((y1 - y3), 2));

s = (a + b + c) / 3;
area=sqrt(fabs((s*(s - a)*(s - b)*(s - c))));

cout << "area= " << area;


return 0;
}

2- CONTROL STRUCTURES: SELECTION AND REPETITION


2.1 SOLUÇÃO DE UM SISTEMA DE EQUAÇÕES LINEARES COM MENSAGENS
DE ERRO: “SISTEMA IMPOSSÍVEL” OU “SISTEMA INCONSISTENTE

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double a, b, c, d, e, f, x, y, n1, n2, d1, d2;

cout << "a= "; cin >> a;


cout << "b= "; cin >> b;
cout << "c= "; cin >> c;
cout << "d= "; cin >> d;
cout << "e= "; cin >> e;
cout << "f= "; cin >> f;

n1 = (c*e - b * f);
n2 = (a*f - c * d);
d = (a*e - b * d);

if (d == 0)
{
if (n1 == 0 || n2 == 0)
cout << "Inconsistent system";
else
cout<<"Impossible system"
}
else
{
x = n1 / d;
y = n2 / d;
cout << "x= "; cin >> x;
cout << "y= "; cin >> y;
}
return 0;
}

2.2 3 NÚMEROS E COMPARAÇÕES

A. DETERMINAR O MAIOR E O MENOR VALOR E APRESENTAR NO ECRÃ


OS NÚMEROS POR ORDEM DECRESCENTE

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

int main()
{
int n1, n2, n3, min, max, midle;
cout << "Please insert 3 numbers: "; cin >> n1 >> n2 >> n3;

if (n1 > n2 && n2 > n3)


{
max = n1; min = n3; midle = n2;
}
else if (n1 > n3 && n3 > n2)
{
max = n1; min = n2; midle = n3;
}
else if (n2 > n1 && n1 > n3)
{
max = n2; min = n3; midle = n1;
}
else if (n2 > n3 && n3 > n1)
{
max = n2; min = n1; midle = n3;
}
else if (n3 > n2 && n2 > n1)
{
max = n3; min = n1; midle = n2;
}
else
{
max = n3; min = n2; midle = n1;
}

cout << max << "<" << midle << "<" << min;
return 0;
}
B. DECIDIR SE OS 3 NÚMEROS SÃO OS COMPRIMENTOS DE UM
TRIÂNGULO

Adicionar ao anterior:

sum = midle + max;


if (sum < max)
cout << "It's no a triangle";
else
cout << "It's a triangle";

return 0;
}
2.3 SOMA DE DOIS NÚMEROS INTEIROS E SE OCORRE UM OVERFLOW OU
UNDERFLOW

int main()
{
int n1, n2, n3, sum;

cout << "Please insert 2 numbers: "; cin >> n1 >> n2;
sum = n1 + n2;
if (sum > INT_MAX)
cout << "Sum OVERFLOW";
else if (sum < INT_MIN)
cout << "Sum UNDERFLOW";
else
cout << sum;
}

2.4 CUSTO DO TRANSPORTE DE MERCADORIA

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

int main()
{
double weight, cost, extra;

cout << "Merchandise weight (g)= "; cin >> weight;


if (weight <= 500)
{
cost = 5;
}
else if (weight > 501 && weight <= 1000)
{
extra = weight - 500;
cost = 5 + 1.5*(extra / 100);
}
else
{
extra = weight - 1000;
cost = 12.5 + 5*(extra / 250);
}
cout << "Transportation cost= " << cost;
return 0;
}
2.5 EQUAÇÃO QUADRÁTICA COM TODOS TIPOS DE SOLUÇÕES
#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
const unsigned int NUMBER_PRECISION = 3;
double A, B, C, delta, r1, r2, p;
cout << "Solution of Ax^2 + Bx + C = 0" << '\n' << "Insert
the coefficients (A B C): ";
cin >> A >> B >> C;

delta = pow(B, 2) - (4 * A*C);


if (delta > 0)
{
r1 = (-B + sqrt(delta)) / (2 * A);
r2 = (-B - sqrt(delta)) / (2 * A);
cout << "The equation has 2 roots: " << r1 << " and "
<< r2;
}
else if (delta = 0)
{
r1 = -B / (2 * A);
cout << "The equation has 1 root: " << r1;
}
else
{
p = -B / (2 * A);
r1=sqrt(fabs(delta))/(2*A);
cout << "The equation has two complex conjugated
roots: " << fixed <<setprecision(NUMBER_PRECISION) << p << " + "
<< fixed << setprecision(NUMBER_PRECISION) << r1 <<"i e " <<
fixed << setprecision(NUMBER_PRECISION) << p << " - " << fixed
<<setprecision(NUMBER_PRECISION) << r1 << "i. ";
}
return 0;
}
2.6 BANCO- DETERMINAR O DINHEIRO DE UM DEPÓSITO A PRAZO

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

int main()
{
int n, i;
double q, j, extra;

cout << "Deposit amount: "; cin >> q;


cout << "years of depositing an amount: "; cin >> n;
cout << "Annual interest rate: "; cin >> j;

for (i = 1; i <= n; i++)


{
extra = q * j;
q = q + extra;
cout << "Amount at the year " << i << " = " << q <<
'\n';
}
return 0;
}
2.7 NÚMEROS PRIMOS

A. DETERMINAR SE UM NÚMERO É PRIMO

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int n, counter, sum;
int divmax = sqrt(n);
cout << "Number= ";
bool isprime = true;
for (int i = 2; i < divmax; i++)
{
if (n%i == 0)
{
isprime = false;
i++;
}
}
if (isprime)
cout << "Is prime!";
else
cout << "Isn't prime!";
return 0;
}

B. ESCRITA DE TODOS OS NÚMEROS PRIMOS MENORES QUE 1000

C. ESCREVER OS 100 PRIMEIROS NÚMEROS PRIMOS


D. DETERMINAR O MAIOR NÚMERO PRIMO QUE PODE SER GUARDADO
NUMA VARIÁVEL DO TIPO UNSIGNED LONG

2.8 ÂNGULOS: SENO, COSSENO E TANGENTE

A. TABELA DE 0 A 90

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int grau;
double seno, cosseno, tg;
const double PI = 3.1414929;
cout << setw(10) << "ang" << setw(10) << "sen" << setw(10)
<< "cos" << setw(10) << "tan" << endl;
for (grau = 0; grau < 90; grau = grau + 15)
{
seno = sin(grau*PI / 180);
cosseno = cos(grau*PI / 180);
tg = tan(grau*PI / 180);
cout << setw(10) << grau << setw(10) << fixed <<
setprecision(7) << seno << setw(10) << setprecision(7) <<
cosseno << setw(10) << setprecision(7) << tg << endl;
}
cout << setw(10) << 90 << setw(10) << 1.000000 << setw(10)
<< 0.000000 << setw(10) << "infinito" << endl;
return 0;
}
B. O INTERVALO E O INCREMENTO SÃO DETERMINADO PELO UTILIZADOR

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int grau_min, grau_max;
double seno, cosseno, tg, inc, grau;
const double PI = 3.1414929;
cout << "grau min = "; cin >> grau_min;
cout << "grau max = "; cin >> grau_max;
cout << "incremento= "; cin >> inc;

cout << setw(10) << "ang" << setw(10) << "sen" << setw(10)
<< "cos" << setw(10) << "tan" << endl;
for (grau = grau_min; grau < grau_max; grau = grau + inc)
{
seno = sin(grau*PI / 180);
cosseno = cos(grau*PI / 180);
tg = tan(grau*PI / 180);
cout << setw(10) << grau << setw(10) << fixed <<
setprecision(7) << seno << setw(10) << setprecision(7) <<
cosseno << setw(10) << setprecision(7) << tg << endl;
}
cout << setw(10) << 90 << setw(10) << 1.000000 << setw(10)
<< 0.000000 << setw(10) << "infinito" << endl;
return 0;
}
2.9 CAPICUAS
A) PARA NÚMEROS DE 3 ALGARISMOS

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int n, n1, n2;

cout << "Insert the number= "; cin >> n;


n1 = n / 100;
n2 = n % 10;
if (n1 == n2)
{
cout << "It's a palindrome";
}
else
cout << "It's not a palindrome";
return 0;
}

B) NÚMEROS COM MAIS DE 3 ALGARISMOS


#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int num, isCap, rev, resto;
cout << "Positive number" << endl; cin >> num;
rev = 0;
isCap = num;
do
{
resto = isCap % 10;
rev = (rev + resto) * 10;
isCap = isCap / 10;
} while (isCap != 0);
if (num == (rev / 10))
cout << "It's a palindrome!" << endl;
else
cout << "It's not a palindrome!" << endl;
return (0);
}
2.10 FATORES PRIMOS

#include <iomanip>
#include <iostream>

using namespace std;

int main() {
int num, div, x, y;
cout << "introduza o numero ="; cin >> num;
div = 2;
for (;;)
{
if (num%div == 0) //divisão exata
{
if (num / div == 1) //resultado 1 acaba com a
conta
{
cout<< num<<'|'<< div<<'\n';
num = num / div;
break;
}
cout << num << '|' << div<<'\n';
num = int(num / div); //torna o número no
próximo
}
else //divisão não exata
{
for (y = 0, x = 1; x <= div; ++x) // teste do
fator primo
if (div%x == 0)
y += x; //y=y+x
if (div + 1 == y)
{
div = y - 1; // divisor passa para o
próximo número primo
}
div++; //inc
}
}
return 0;
}
2.11 SOMA DOS PRIMEIROS N FATORES

A) CONSTANTE 

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

int main()
{
float sum=4;
int n, den;

cout << "Number of terms= "; cin >> n;

for (int i = 2; i <= n; i++)


{
den = pow((-1), n)*(2 * i - 1);
sum = sum - 4. / den;
}
cout << "PI=" << sum;
return 0;
}

B) CONSTANTE NEPER

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int n, i, a, fat;
double e;
cout << "Please insert the number of terms: "; cin >> n;
e = 1;
for (i = 2; i <= n; i++)
{
fat = 1;
for (a = i - 1; a != 1; a--)
{
fat = fat * a;
}
e = e + (1.0 / fat);
}
cout << "e= " << e;
}

C) NEPER^X
#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
int n, i, a, fat, num, index;
double e;
int x;
cout << "Please insert the number of terms: "; cin >> n;
cout << "x value="; cin >> x;
e = 1;
for (i = 2; i <= n; i++)
{
index = -(i - 1);
num = pow(x, index);
fat = 1;
for (a = i - 1; a != 1; a--)
fat = fat * a;
e = e + (num / fat);
}
cout << "e= " << e;
}

2.12 REPETIÇÃO DO ANTERIOR, MAS COM A PRECISÃO DEFINIDA PELO


UTILIZADOR

Neste caso era necessário criar ciclos do… while (fabs(somaNew-


somaOld)>pre);

2.13 PROGRAMA QUE LÊ UMA SEQUÊNCIA DE NÚMEROS INTEIROS E


DETERMINA A: SOMA, STD, O MAIOR E O MENOR NÚMERO NAS
SEGUINTES SITUAÇÕES

A) O COMPRIMENTO DA SEQUÊNCIA É INDICADA PELO UTILIZADOR

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
int comp, n, s, s_n, l_n;
double sum, mean, std;
s_n = 0; l_n = 0;
sum = 0;
mean = 0.0;
std = 0.0;
s = 0;
cout << "Lenght of sequence= "; cin >> comp;

for (int i = 1; i <= comp; i++)


{
cout << "n= "; cin >> n;
sum = sum + n;
mean = sum / i;

s = s + pow((n - mean), 2);


std = sqrt(s / i);

if (n < s_n)
s_n = n;
else if (n > l_n)
l_n = n;

}
cout << "sum= " << sum<<endl;
cout << "mean= " << mean << endl;
cout << "std= " << sum << endl;
cout << "smallest number= " << s_n << endl;
cout << "largest number= " << l_n << endl;
}

B) O FIM DA SEQUÊNCIA É INDICADO PELO VALOR 0 (NÃO É


CONSIDERADA PARTE DA SEQUÊNCIA) E NO FIM O PROGRAMA
INDICA O FINAL DA SEQUÊNCIA
C) O FIM DA SEQUÊNCIA É INDICADO QUANDO O UTILIZADOR
ESCREVE CTRL-Z

2.14 RAIZ QUADRADA

A) CALCULAR A RAIZ QUADRADA

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
float rq, rqn, rqn2, dif, delta;
int n, nMaxIter, counter;

cout << "Number= "; cin >> n;


cout << "delta= "; cin >> delta;
cout << "nMaxIter= "; cin >> nMaxIter;
rq = 1; counter = 0;
do
{
rqn = (rq + n / rq) / 2;
rqn2 = sqrt(rqn);
dif = n - rqn2;
counter++;
rq = rqn;

} while (counter != nMaxIter || dif <= delta);


cout << "Raiz quadrada de " << n << "= " << rq;
return 0;
}

B) MODIFICAÇÃO DA ALÍNEA ANTERIOR COM O NÚMERO DE CASAS


DECIMAIS DO DELTA E COMPARAR COM A FUNÇÃO SQRT() DE C

2.15 TABELAS DA MULTIPLICAÇÃO

#include <iomanip>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
//Tabuada
//teste das tabuadas da multiplicação entre 2 e 9
int randomBetween(int n1, int n2)
{
return rand() % (n2 - n1 + 1) + 2;
//este +1 serve para indicar a partir de onde é que se
inicia o intervalo
}
int main()
{
srand(time(NULL));
int a, b, result, ans;
time_t t1, t2, time_elapsed;
a = randomBetween(2, 9);
b = randomBetween(2, 9);
result = a * b;
t1 = time(NULL);
cout << a << '*' << b << '='; cin >> ans;
t2 = time(NULL);
time_elapsed = t2 - t1;
if (ans != result)
{
cout << "Very Bad!";
}
else
{
if (static_cast<double>(time_elapsed) <= 5)
{
cout << "Good!";
}
else if (time_elapsed > 5 || time_elapsed <= 10)
{
cout << "Satisfactory";
}
else
cout << "Insufficient";
}
}

2.16 SIMULAÇÃO DE UMA CALCULADORA

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
const unsigned int NUMBER_PRECISION = 3;
double n1, n2, result;
char operation, rpt, anotherOperation;
do
{
cout << " n1 operator n2= ";
cin >> n1 >> operation >> n2;
bool validOperation = true;
switch (operation)
{
case '+':
result = n1 + n2;
break;
case '-':
result = n1 - n2;
break;
case '*':
result = n1 * n2;
break;
case '/':
result = n1 / n2;
break;
default:
validOperation = false;
}
if (validOperation)
{
cout << fixed << setprecision(NUMBER_PRECISION);
cout << n1 << ' ' << operation << ' ' << n2 << "
= " << result
<< endl;
}
else
cerr << "Invalid operation !\n";
cout << "Another operation (Y/N) ? ";
cin >> anotherOperation;
anotherOperation = toupper(anotherOperation);
} while (anotherOperation == 'Y');
return 0;
}

3. FUNCTIONS
3.1 CALCULAR A ÁREA DO TRIANGULO (1.6), MAS COM FUNÇÕES
#include <iomanip>
#include <iostream>

using namespace std;

double distance(double x1, double y1, double x2, double y2)


{
return (sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2)));
}

double area(double x1, double y1, double x2, double y2, double
x3, double y3)
{
double a, b, c, s, area;
a = distance(x1, y1, x2, y2);
b = distance(x2, y2, x3, y3);
c = distance(x1, y1, x3, y3);

s = (a + b + c) / 3;
return sqrt(fabs((s*(s - a)*(s - b)*(s - c))));
}

int main()
{
double x1, y1, x2, y2, x3, y3;
cout << "Point 1 coordinates (x1, y1)= "; cin >> x1 >> y1;
cout << "Point 2 coordinates (x2, y2)= "; cin >> x2 >> y2;
cout << "Point 3 coordinates (x3, y3)= "; cin >> x3 >> y3;
double A = area(x1, y1, x2, y2, x3, y3);
cout << A;
}

3.2 FUNÇÃO IS PRIME()

You might also like