C#中如何实现正确向上取整?城镇人口计算取整异常求助
问题分析与解决方案
你的问题核心是计算最终人口时的类型转换顺序错误——在调用取整方法前,你已经通过(int)(intial_population * value)直接截断了计算结果的小数部分,后续的Convert.ToInt32、Math.Round或Math.Ceiling自然无法改变已经被截断的整数。
比如实际计算结果是26891.9,强转int会直接丢掉.9得到26891,之后再执行取整操作也只能得到这个值,和预期的26892不符。
修复步骤
- 保留计算结果的完整浮点值,不要提前强转
int - 使用
Math.Ceiling对完整的计算结果进行向上取整(人口是整数,增长后的小数部分需要向上取整) - 再将取整后的结果转换为整数类型
修正后的完整代码
public class Program { public static void Main(string[] args) { // Keep the following line intact Console.WriteLine("==========================="); Console.WriteLine("Enter the simulation period (whole years):"); int years = Convert.ToInt32(Console.ReadLine()); if (years < 1) { Console.WriteLine("Simulation cancelled: no years."); Console.ReadLine(); return; } Console.WriteLine("Enter the number of towns:"); int town = Convert.ToInt32(Console.ReadLine()); if (town < 1) { Console.WriteLine("Simulation cancelled: no towns."); Console.ReadLine(); return; } for (int i = 1; i <= town; ++i) { Console.WriteLine("Enter the name of the town:"); string name = Console.ReadLine(); Console.WriteLine("Enter the initial population of the town:"); int initial_population = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the growth rate of the town:"); Decimal growth = Convert.ToDecimal(Console.ReadLine()); double growthFactor = Math.Pow((double)growth, years); double populationCalculation = initial_population * growthFactor; int final_population = (int)Math.Ceiling(populationCalculation); Console.WriteLine("The population of {0} goes from {1} to {2} with growth factor {3} after {4} years.", name, initial_population, final_population, growth, years); Console.ReadLine(); } } }
额外优化说明
- 修正了变量名拼写错误:
intial_population→initial_population - 在取消模拟的分支后添加
return,避免后续代码继续执行(原代码逻辑存在漏洞) - 简化了类型转换流程,减少不必要的类型转换操作,提升代码可读性
内容的提问来源于stack exchange,提问作者jose mathew
相关产品推荐
相关产品推荐

