在切片中过滤数字的问题

huangapple go评论85阅读模式
英文:

Problem with filter numbers in slice by range

问题

我有一个问题,关于我需要过滤并输入到evenNumbers数组中的范围数字,但是我得到了编译错误。

使我编译通过!

//
// 我还没有完成
package main_test

import (
"reflect"
"testing"
)

func TestFilterEvenNumbers(t *testing.T) {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

evenNumbers := []int{} // 使用range来过滤偶数

for _, evenNumber := range numbers {
    if evenNumber % 2 == 0 {
        evenNumbers = append(evenNumbers, evenNumber)
    }
}

if !reflect.DeepEqual(evenNumbers, []int{2, 4, 6, 8, 10}) {
    t.Errorf("evenNumbers不包含所有所需的偶数,得到%v", evenNumbers)
}

}

请检查下面的输出:

command-line-arguments_test [command-line-arguments.test]

exercises/range/range3/main_test.go:18:22: 无法将2(无类型的int常量)转换为[]int
exercises/range/range3/main_test.go:19:27: 无法将append(numbers)(类型为[]int的值)作为赋值语句中的int类型使用
FAIL command-line-arguments [构建失败]
FAIL

英文:

I have a problem with the range numbers which I have to filter and enter into the evenNumbers array, but I get compilation errors

Make me compile!
//
// I AM NOT DONE
package main_test
 
import (
    "reflect"
    "testing"
)
 
func TestFilterEvenNumbers(t *testing.T) {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 
    evenNumbers := []int{} // use range to filter even numbers
 
    for _, evenNumbers := range numbers {
        if numbers % 2 {
            evenNumbers = append(numbers)
        }

    }
 
    if !reflect.DeepEqual(evenNumbers, []int{2, 4, 6, 8, 10}) {
        t.Errorf("evenNumbers does not contain all the required even 
        numbers, got %v", evenNumbers)
    }
}

Check the output below

# command-line-arguments_test [command-line-arguments.test]
exercises/range/range3/main_test.go:18:22: cannot convert 2 (untyped int constant) to []int
exercises/range/range3/main_test.go:19:27: cannot use append(numbers) (value of type []int) as type int in assignment
FAIL    command-line-arguments [build failed]
FAIL

答案1

得分: 1

这段代码完全错误,你使用了数组而不是数组元素,并且没有正确检查 % 条件。循环应该是这样的:

for _, number := range numbers {
	if number%2 == 0 {
		evenNumbers = append(evenNumbers, number)
	}
}
英文:

This code is totally wrong, you are using arrays instead of array
elements and don't check % condition correctly. The loop should be:

for _, number := range numbers {
	if number%2 == 0 {
		evenNumbers = append(evenNumbers, number)
	}
}

huangapple
  • 本文由 发表于 2023年3月6日 00:40:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75643780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定