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

Flutter工作应用中实现指定重量取整规则的计算公式求助

解决方案:重量计费的取整逻辑

嘿,根据你给出的示例,你的计费规则其实是按每1000单位为一个阶梯的向上取整(天花板取整),刚好能完美匹配所有测试场景。

核心逻辑说明

简单来说,就是把重量值除以1000后,向上取整得到最终的theFee:

  • 当重量≤1000时,结果为1;
  • 1001≤重量≤2000时,结果为2;
  • 以此类推,哪怕重量刚好是1000的整数倍,也按该整数计算;只要超过整数倍1单位,就进一位。

Flutter/Dart 实现方案

这里给你两种可行的实现方式:

方式1:使用ceil()方法(需要引入math库)

这是最直观的实现,利用Dart的天花板取整函数:

import 'dart:math';

int calculateFee(int theWeight) {
  // 先转为double做除法,再向上取整,最后转成int类型
  return (theWeight / 1000).ceil();
}

// 测试示例
void main() {
  print(calculateFee(1));      // 输出: 1
  print(calculateFee(999));    // 输出: 1
  print(calculateFee(1000));   // 输出: 1
  print(calculateFee(1001));   // 输出: 2
  print(calculateFee(2000));   // 输出: 2
  print(calculateFee(2001));   // 输出: 3
}

方式2:纯整数运算(无需额外库)

如果不想引入math库,或者担心浮点运算的精度问题,可以用整数运算模拟向上取整,性能也更优:

int calculateFee(int theWeight) {
  // 给重量加上999后做整数除法,等价于向上取整
  return (theWeight + 999) ~/ 1000;
}

// 测试示例(结果和上面完全一致)
void main() {
  print(calculateFee(1));      // 输出: 1
  print(calculateFee(999));    // 输出: 1
  print(calculateFee(1000));   // 输出: 1
  print(calculateFee(1001));   // 输出: 2
  print(calculateFee(2000));   // 输出: 2
  print(calculateFee(2001));   // 输出: 3
}

这个整数运算的原理很简单:给重量加上999后,再用整数除法~/除以1000,就能自动把不足1000的部分"凑整"到下一个整数,完美匹配你的需求。

内容的提问来源于stack exchange,提问作者onnedaay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:14:08