简体   繁体   中英

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

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

  • %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");
    }
}

"%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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM