You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:43:15