如何在NetLogo中让百分比比率显示为整数而非小数?
如何将NetLogo监视器的百分比显示为整数?
你只需要用NetLogo的取整命令包裹计算结果,就能把小数百分比转换成整数显示。这里有几种常用方案,你可以根据需求选择:
1. 四舍五入到最近整数(最常用)
使用round()命令,它会自动把小数四舍五入到最接近的整数。同时为了避免企业总数为0时出现除以0的错误,我给代码加了一个简单的判断:
to-report percentage-of-firms-at-home ;; monitors the % of firms which produce at home if count firms = 0 [ report 0 ] report round( ( count firms with [ ycor > 0 ] ) / count firms * 100 ) end to-report percentage-of-offshored-firms ;; monitors the % of offshored firms if count firms = 0 [ report 0 ] report round( ( count firms with [ ycor < 0 ] ) / count firms * 100 ) end
2. 向下取整(舍去小数部分)
如果你希望直接截断小数,只保留整数部分(比如56.9%显示为56%),可以替换成floor()命令:
report floor( ( count firms with [ ycor < 0 ] ) / count firms * 100 )
3. 向上取整(强制进一位)
如果需要不管小数多少都进一位(比如56.1%显示为57%),就用ceiling()命令:
report ceiling( ( count firms with [ ycor < 0 ] ) / count firms * 100 )
另外,我注意到你已经给企业定义了offshored?变量,其实可以直接用这个变量统计,不用依赖坐标判断,代码会更清晰(前提是你的坐标和变量状态是同步的):
to-report percentage-of-offshored-firms if count firms = 0 [ report 0 ] report round( ( count firms with [ offshored? = true ] ) / count firms * 100 ) end
修改完代码后,重新关联监视器就能看到整数形式的百分比啦!
内容的提问来源于stack exchange,提问作者user11277648
相关产品推荐
相关产品推荐

