printf does not show the expected value

Asked

Viewed 145 times

1

I’m having trouble showing off some printf, for example:

printf("\nDigite as horas : %d");

And at the time of displaying the message, it appears with a number on the side, for example:

Enter the hours: 89676

What’s the mistake in that? I declare the correct variables, but in the display appears this number, what can I do to take them out?

  • 1

    Probably it is reading some invalid memory region, since you specified that you would pass a number as argument (%d) but no pass (example - note that a different number has been displayed as the content of the memory at that point is undefined). If you do printf("\nDigite as horas : %d", 10); he will print Digite as horas: 10. If you don’t want any number, remove the %d and it will print Digite as horas:.

  • Thank you Renan, but I’ve taken the %d of the question that I’m asking and it’s still the same :/

  • 2

    I suggest [Dit] the question putting more of your real code, because only with this example is it difficult to know what is really happening...

  • @Karolaynesantos Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? Need something to be improved?

2 answers

4

Is that all there is to the line? So it makes sense to have a "garbage" on the screen. The %d indicates that there will be placed an integer value. What value are you passing to the function to put there? None. Then he takes whatever he finds in the memory. If he passes a value, it will be printed.

On the other hand, I think you’re willing to use the function scanf() to read the time:

#include <stdio.h>

int main(void) {
    int i;
    printf("\nDigite as horas : %d"); //pega qualquer coisa para exibir
    printf("\nDigite as horas : %d", 12); //aqui imprime o 12
    printf("\nDigite as horas :"); //não tem dados variáveis para imprimir
    scanf ("%d", &i); //pede o dado aqui
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • The scanf() should only have the "%d". All other characters are too many. Also, always validate the value returned: if (scanf("%d", &i) != 1) /* erro */;

  • It’s true, I was going to ride one thing and I rode another in a hurry.

0

If you want to enter the hours first you should receive the hours for example

int main(){
    int horas;
    printf("Digite as horas: ");
    scanf("%d", &horas);
    // Depois devolve o valor lido através de um printf
    printf("São %d horas", horas);
    return 0;
}

Browser other questions tagged

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