Home > Net >  why is the output of my program 0.000000 when it should be the value i entered when prompted. below
why is the output of my program 0.000000 when it should be the value i entered when prompted. below

Time:07-30

I am trying to execute this code. but the number variable isn't storing the value I input,what could be posssible explanations of this behaviour.

#include <stdio.h>
int main(){
    float number;
    
    printf("enter a value\n");
    scanf("%5.3f",&number);
    printf("u entered : %f",number);

    return 0;
}

and below is sample of its execution

enter a value
78.467  
u entered : 0.000000

Why isn't number storing the value 78.467

CodePudding user response:

"%5.3f" in scanf("%5.3f",&number); is an invalid format so the result is undefined behavior (UB).

The "5" is OK. It limits the number of characters read in the conversion to at most 5.

".3" is not part of a valid conversion specification.

Save time, enable all warnings. @David Ranieri

// scanf("%5.3f",&number);
if (scanf("%f",&number) != 1) {
  fprintf(stderr, "Non-numeric input\n");
  return -1; 
}

CodePudding user response:

  • %5.3f is not a valid scanf format. It should be %f.
  • You also do not check that scanf succeeds. Always do.

Example:

#include <stdio.h>
int main() {
    float number;

    puts("enter a value");
    if(scanf("%f", &number) == 1) {          // check that it succeeds
        printf("u entered : %5.3f", number); // in printf %5.3f is ok
    } else {
        puts("Erroneous input");
    }
}
  • Related