Sonar Sensor Large Range Error

Currently making basic code for a robot using RobotC. The code has the robot go forward until the sonar sensor detects something below 20 inches. When it detects something below 20 inches it goes backward for 1 second. I realized when something is too far it backs up. When nothing is within a certain range the sonar puts -1. I fixed it by making it back up between 0 and 20 but it still does this. I read somewhere that it gives about 20 readings a second and that could be causing the issue. My thinking is once something is out of range it gives about 20 readings between the max distance and -1 and one of those numbers is in my range causing it to go back when it shouldn’t. Am I correct and how do I fix it?
Edit: The Sensor is not IQ and is EDR

Why don’t you try just experimenting with the sensor itself? Write a simple code that prints the sensor reading to the brain or something and then slide it along the floor and check what it’s sensing. I found the IQ distance sensor to be inaccurate to ± 2 inches or so, but that wouldn’t seem to be your problem.