Males will grow up, learn their heritage, and seek revenge. Also, it would not be acceptable for the Midianite male to marry a Hebrew woman (when they did grow up). And then the following reasons also:
https://www.studylight.org/commentary/numbers/31-17.html
George Haydock's Catholic Bible Commentary
Of children. Women and children, ordinarily speaking, were not to be
killed in war, Deuteronomy xx. 14. But the great lord of life and
death was pleased to order it otherwise in the present case, in
detestation of the wickedness of this people, who by the counsel of
Balaam, had sent their women amongst the Israelites on purpose to draw
them from God. (Challoner) --- Only those who were under twelve would
be thus reserved; and as their tender minds might yet receive the
impressions of virtue, by a proper education, they might, one day, be
married by some of the Hebrews. The boys were all slain, either
because they might be inclined to resent the injury done to their
relations, or because they were all consecrated to Beelphegor; the
first-born to be his priests, the rest to be victims, if necessary, to
avert any evil. For "the heathens in cold blood," says Paine, "offered
their children in sacrifice to Baalpeor." It was on this account, that
the killing of all the first-born in Egypt, was felt so terribly, as
the people could not lawfully approach their gods. (Forbes) --- Moses
did not reserve the girls for the purpose of debauchery, as Paine
ignorantly pretends; for that was contrary to his own laws, nor did he
wantonly kill the innocent, which he also strictly forbade, and which
he would have been still more afraid to do, if he had been an
impostor. But he preserved the lives of those girls who might be
presumed innocent, and who might live to do good, while he took the
revenge of the Lord (ver. 3,) upon the rest. (Haydock)