Floats breaking my code

前端 未结 1 390
半阙折子戏
半阙折子戏 2021-01-29 03:04

I\'ve written a program that returns the median value of a user-defined array. While I\'ve put a few checks in my code (array size can not be negative) I keep running into one i

相关标签:
1条回答
  • 2021-01-29 04:03

    You're reading into an int:

    int x;
    ...
    cin >> x;
    

    So it will read what it can, then stop at e.g. a . and leave the rest on the stream (like if the user enters "123.4" you'll get 123 and then ".4" won't be consumed from the input stream).

    Instead, you could read into a float:

    float x;
    ...
    cin >> x;
    

    And do the appropriate math.

    Alternatively you could read into a string and parse it into a float. That way you won't get stuck at letters and such either.

    And the final option is to read into an int but handle any errors and skip the bad input, which is detailed at How to handle wrong data type input so I won't reproduce it here.

    Which option you choose really just depends on what you want the behavior of your program to be and how strictly you want to validate input (e.g. round vs. fail if "2.5" is entered but an integer is expected, how do you want to handle "xyz" as input, etc.).

    0 讨论(0)
提交回复
热议问题