How to calculate months of a year from a decimal number?

5
#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("\tPrograma para saber quanto demora a tornar-se génio!\n\n");
    float tempo(int horas);
    float converter(float x);
    int num_horas;
    float dias,anos;
    printf("Quantas horas vai dedicar por dia para ser genio?");
    scanf("%d",&num_horas);
    dias=tempo(num_horas);
    anos=converter(dias);
    printf("Voce vai demorar %.1f dias ou seja aproximadamente %.2f anos para ficar génio",dias,anos);
    return 0;
}
//funcao para converter dias em anos
float converter(float x) {
if(x>366) {
    int um_ano=366;
    float troca=x/um_ano;
    return troca;
}
}
//funcao que converte as horas dedicadas em dias;
float tempo(int horas) {
    float dias;
    dias=10000/horas;
    return dias;

}

The code works, but I wanted to improve it in that part when it does printf and tells how old it takes to be a genius. It does a float (on purpose), but I wanted to convert the decimal part into months. For example 4.22 years or I wanted to be 4 years and I do not know how many months (.22).

I accept constructive criticism.

    
asked by anonymous 31.12.2015 / 19:20

1 answer

5

I did what I understood. Obviously it is not very precise, it can give strange results in some cases, but just for a good exercise.

There are several things that could be improved in a specific context. As it is exercise, having functions can make sense, but to do something so simple that it will only be used once, it does not make sense to have them.

Notice the little details that I've rewritten to stay organized, see how it's easier to read and leaner. Could be even more so. Has variable left over. Note that I have given better names for the functions, so you do not need comments. I got other little flaws.

#include <stdio.h>

float converterDiasEmAnos(float dias) {
    return dias / 365;
}
float converterHorasEmDias(int horas) {
    return 10000 / horas;
}
int obterMeses(float anos) {
    return (anos - (int)anos) / (1.0f / 12.0f) + 1;
}
int main() {
    printf("\tPrograma para saber quanto demora a tornar-se genio!\n\n");
    int num_horas;
    printf("Quantas horas vai dedicar por dia para ser genio? ");
    scanf("%d", &num_horas);
    float dias = converterHorasEmDias(num_horas);
    float anos = converterDiasEmAnos(dias);
    int meses = obterMeses(anos);
    printf("\nVoce vai demorar %.1f dias, ou seja, aproximadamente %d anos e %d meses para ficar genio", dias, (int)anos, meses);
    return 0;
}

See working on ideone .

    
31.12.2015 / 19:59