I’m having trouble separating an integer from a variable

Asked

Viewed 69 times

0

Good morning Guys, I’m having trouble on the following issue.

Write a program that receives a time provided by the user as a single integer (hhmmss) and write time in the form: hh:mm:ss. The program uses a function which receives the integer containing the time and returns that time in variables separate: hour, minute and second.

I have thought of several ways this and all that I have been able to develop so far, but the result comes out very strange as for example I enter 131010 he returns to me: 3960832: 0: 4200992

inserir a descrição da imagem aqui


#include<stdio.h>
#include<stdlib.h>
 int horario(int hhmmss,int hh,int mm,int ss);
 int main(){
 int hhmmss, hh, mm, ss;
 horario(hhmmss,hh,mm,ss);

  printf("%d: %d: %d ",(&hh,&mm,&ss));
}
 int horario(int hhmmss,int hh,int mm,int ss){
  printf("Insira um horario no formato hhmmss: \n");
  scanf("%d",&hhmmss);
  hh = hhmmss/10000;
  mm = (hhmmss % 10000)/100;
  ss = hhmmss % 100;
}

Sorry for the code sent as image.

  • You are passing parameters to your function by value and is trying to use the result of calculations performed in its function in the calling function (in the main case). Nz reality is printing memory junk. Search by passing parameters by reference.

  • Okay, now I passed the memory address to the 3 variables printf("%d: %d: %d ",(&hh,&mm,&ss)); I was able to separate the mm and ss but hh still receives memory junk

  • Then show how was your time function, not as image but as text, as is recommended on this site. Manual on how NOT to ask questions

1 answer

0


Solution 1) Passing parameters by reference (pointer):

#include <stdio.h>

void horario(int n, int *h, int *m, int *s)
{
    *h = n / 10000;
    *m = (n % 10000) / 100;
    *s = n % 100;
}

int main(void)
{
    int entrada, horas, minutos, segundos;
    printf("Insira um horario no formato hhmmss: ");
    scanf("%d",&entrada);
    horario(entrada, &horas, &minutos, &segundos);
    printf("%02d:%02d:%02d\n", horas, minutos, segundos);
    return 0;
}

Solution 2) Returning a struct:

#include <stdio.h>

typedef struct hora_s
{
    int horas;
    int minutos;
    int segundos;
} hora_t;

hora_t horario(int n)
{
    hora_t h;
    h.horas = n / 10000;
    h.minutos = (n % 10000) / 100;
    h.segundos = n % 100;
    return h;
}

int main(void)
{
    int entrada;
    hora_t h;
    printf("Insira um horario no formato hhmmss: ");
    scanf("%d",&entrada);
    h = horario(entrada);
    printf("%02d:%02d:%02d\n", h.horas, h.minutos, h.segundos);
    return 0;
}

Browser other questions tagged

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