Menu
CoddyTech

挑战:数字求和

本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 93 课,共 94 课。

challenge icon

挑战

简单

在这个挑战中,你将创建一个函数,根据特定条件计算列表中数字的总和。

你有一个整数列表,需要完成 sumWithCondition 函数,只累加符合特定条件的数字。

这个函数应该:

  • 计算列表中所有大于 threshold 值的数字之和
  • 总和超过 maxSum 值后立即停止累加(最终总和可能大于 maxSum)
  • 返回最终总和

重要:函数会在加上导致总和超过 maxSum 的数字之后停止累加。这意味着最终结果可能大于 maxSum。

示例:如果大于 threshold 的数字是 [15, 20, 25, 30],且 maxSum 是 50:

  • 加上 15:sum = 15(继续)
  • 加上 20:sum = 35(继续)
  • 加上 25:sum = 60(超过 50,因此在这里停止)
  • 结果:60(不是 50)

亲手试试

void main() {
  // 测试用例
  List<int> numbers = [5, 10, 15, 20, 25, 30];
  
  // 将大于 12 的数相加,最大总和为 50
  int result = sumWithCondition(numbers, 12, 50);
  print('Sum of numbers > 12 (max 50): $result');
  
  // 将大于 8 的数相加,最大总和为 100
  result = sumWithCondition(numbers, 8, 100);
  print('Sum of numbers > 8 (max 100): $result');
}

// TODO: 完成这个函数,根据条件将数字相加
int sumWithCondition(List<int> numbers, int threshold, int maxSum) {
  int sum = 0;
  
  // TODO: 遍历 numbers 列表
  // TODO: 只将大于 threshold 的数加到 sum 中
  // TODO: 如果 sum 超过 maxSum,就停止相加
  
  return sum;
}

基础知识中的所有课

自己练习: Dart 在线编译器