-3

I'm writing a simple C program to classfiy distances into certain ranges such as short long or medium I understand that C will cancel out numbers after the decimal point to store as an int. So that confuses me that why can't I type in a number such as 7.5 during scanf? as that will leads me to error.

Why can't it just read in as 7 into my scanf? Is it because a keystroke of "." simply couldnt be accepted in declaring an int variable? Why is it exactly?

LCS
  • 3
  • 4

1 Answers1

4

I guess you mean 7.5 rather than 7+.+5.

This is just the way the scanf function works. When you specify %d, it means "Read digits of an integer". When you specify %f,it means "Read floating point value". The documentation for scanf gives the full detail about what is read and what stops.

If you want to read values with decimals and ignore the decimal, you have many options:

  • Read a double and convert to int afterwards
  • Read an int and check for a following . ; read another int if you find one
  • don't use scanf; read a string and do your own parsing
  • etc.

Personally I'd prefer not to use scanf, it has unavoidable UB when reading integral or floating point values.

M.M
  • 130,300
  • 18
  • 171
  • 314