1
I have a question asking to calculate a due value of each car by parking and print on a tabular exit, ex:
Carro Horas Valor
1 2.0 2.0
2 3.0 2.0
3 4.0 2.5
TOTAL 9.0 6.5
I was basically having trouble reading the value of hours and printing on a tabular output the values of car number, hours and value(The error was because reading the hours interfere with tabular output). So, I made this program with the switch structure but I think this is not the best way to solve this problem because I had to create a variable for each thing (time of car 1, time of car 2, value to pay of car 1.... ). Any indication? (OBS, I need the function calculateTaxa, the function Imprimetela is not required. Also I don’t know anything yet about arrays, pointers and so on, only functions).
#include <stdio.h>
#include <math.h>
double calcularTaxas(float);
void ImprimeTela(int, double, double);
int main(){
double horas, horas1, horas2, a , b, c, totalHoras = 0, totalTaxa = 0;
for (int cont = 1; cont <=3; ++cont){
printf("Digite quantas horas cada carro ficou no estacionamento: ");
scanf("%lf", &horas);
switch (cont){
case 1:
a = calcularTaxas(horas);
horas1 = horas;
break;
case 2:
b = calcularTaxas(horas);
horas2 = horas;
break;
case 3:
c = calcularTaxas(horas);
break;
default:
break;
}
totalHoras = horas + horas1 + horas2;
totalTaxa = a + b + c;
}
for (int cont = 1; cont <= 4; ++cont)
switch (cont){
case 1:
printf("\n%s\t\t%s\t\t%s\t\t\n","Carro", "Horas", "Valor");
ImprimeTela(cont, horas1, a);
break;
case 2:
ImprimeTela(cont, horas2, b);
break;
case 3:
ImprimeTela(cont, horas, c);
break;
case 4:
ImprimeTela(cont, totalHoras, totalTaxa);
default:
break;
}
return 0;
}
// função para calculo do valor a ser pago para cada carro
double calcularTaxas(float horas){
float valor;
if (horas <= 3)
valor = 2;
else if (horas >= 20)
valor = 10;
else
valor = 2 + ceil(horas - 3) * 0.5;
return valor;
}
void ImprimeTela(int a, double b, double c){
if (a == 4)
printf("\n%s\t\t%.1f\t\t%.1f\t\t\n", "TOTAL", b, c);
else
printf("%d\t\t%.1f\t\t%.1f\t\t\n", a, b, c);
}
Think about it: if from now on you needed to register 5 cars you would have to change your code by adding 2 more cases? I don’t think that’s a good solution. After treating each car you just need to print the line referring to it and accumulate the print values of the total at the end of the program.
– anonimo