counting how many days left to finish the year

Asked

Viewed 1,147 times

0

I was making a program in c++ to count how many days to finish the year from a date in the format dd/mm/yyyy but according to the date of the month I enter it always gives the same result type:

if I type 18/02/2018 or 12/02/2018 it says 340 days or if I type 14/03/2018 or 20/03/2017 it shows that 275 days are missing. Why is he doing this?

the program is this below.

#include <stdio.h>


int main ()
{
 int falta_dias = 0;
 int dia, mes, ano;
 int dias_mes[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

 do{
    printf("Digite uma data no formato dd/mm/yyyy: ");
    scanf("%d/%d/%d", &dia, &mes, &ano);

    if(dia > 31 || dia < 1)printf("\n\tDia %d invalido.!!\n\tDigite um dia de 01 a 31\n",dia);

    if(mes > 12 || mes < 1)printf("\n\tMes %d invalido.!!\n\tDigite um mes de 01 a 12\n",mes);

   }while((dia > 31 || dia < 1) || (mes > 12 || mes < 1));

   dias_mes[1] = (ano%4 == 0 || ano%400 == 0 && ano%100 != 0) ? 29 : 28;

   for(int i = mes; i<12; i++)
   falta_dias += dias_mes[i];

   printf("\n\nFaltam %d dias para terminar o ano %04d.\n\n", falta_dias,ano);

 return 0;
}
  • 1

    Whenever you put code in your questions format it with the question formatting button {} or using the Ctrl+K shortcut

1 answer

3


You are only counting the days from the next month to which you indicate in the standard input (your loop for(int i = mes; i<12; i++)). Add the remaining days in the chosen month to your code:

for(int i = mes; i<12; i++)
falta_dias += dias_mes[i];

falta_dias+=dias_mes[mes-1] - dia; // conta os dias restantes do mes indicado na entrada padrão
printf("\n\nFaltam %d dias para terminar o ano %04d.\n\n", falta_dias,ano);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.