I've written about this a couple times before:
and
Let me know if those answers help! the tl;dr is that a midshipman might go to sea as early as 11 or 12, then spend some time fictionally at sea being trained in mathematics, then be able to stand for a lieutenant's examination when he "appeared to be" 18 or so.
The mid in Honblower was in parlous straits, but in perhaps less pitiable circumstances than the many men who passed their exam and were never commissioned.
(Separately -- next, read the Aubrey/Maturin novels by Patrick O'Brian. Nothing wrong with Hornblower, but O'Brian is, quite honestly, my generation's Jane Austen.)