Planets are believed to have formed through the accumulation of a large number of small bodies. In the case of the gas-giant planets Jupiter and Saturn, they accreted a significant amount of gas directly from the protosolar nebula after accumulating solid cores of about 5-15 Earth masses. Such models, however, have been unable to produce the smaller ice giants Uranus and Neptune at their present locations, because in that region of the Solar System the small planetary bodies will have been more widely spaced, and less tightly bound gravitationally to the Sun. When applied to the current Jupiter-Saturn zone, a recent theory predicts that, in addition to the solid cores of Jupiter and Saturn, two or three other solid bodies of comparable mass are likely to have formed. Here we report the results of model calculations that demonstrate that such cores will have been gravitationally scattered outwards as Jupiter, and perhaps Saturn, accreted nebular gas. The orbits of these cores then evolve into orbits that resemble those of Uranus and Neptune, as a result of gravitational interactions with the small bodies in the outer disk of the protosolar nebula.