Spec: Array types:
The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int
.
Your length in [s]float64
is not a constant.
Use a slice instead of an array type, and know that you have to use integer type for the length, e.g.:
var mark []float64 = make([]float64, int(s))
Or short:
mark := make([]float64, int(s))
Going forward, always use integer types (e.g. int
) for indices. You can declare it in for
like:
for i := 0; i < len(mark); i++ {
fmt.Scanf("%f", &mark[i])
}
Or you can even use for ... range
to range over the indices of the slice:
for i := range mark {
fmt.Scanf("%f", &mark[i])
}
I would also use int
type everywhere: the number of subjects and marks themselves do not have a meaning if they are non integers.
Also fmt.Scanf()
does not consume newline, subsequent fmt.Scanf()
call will return immediately with an error.
You should also check errors or successfully parsed values, both which are returned by the fmt.Scan*()
functions.
Also you don't have to loop the slice twice, you can calculate total (the sum) in the first.
Going even more forward, you don't even have to store the marks in the slice, you could just ask the entered number of marks, calculate sum on the fly and print the average.
Something like this:
var n, total, mark int
fmt.Println("Number of subjects:")
fmt.Scanln(&n)
for i := 0; i < n; i++ {
fmt.Scanln(&mark)
total += mark
}
fmt.Println("Average:", float64(total)/float64(n))
If you were to add all the required checks, it could look like this:
var n, total, mark int
fmt.Print("Number of subjects: ")
if _, err := fmt.Scanln(&n); err != nil || n <= 0 {
fmt.Println("Wrong number!")
return
}
for i := 0; i < n; i++ {
fmt.Printf("Enter %d. mark: ", i+1)
if _, err := fmt.Scanln(&mark); err != nil || mark < 1 || mark > 5 {
fmt.Println("Wrong mark, enter it again!")
fmt.Scanln()
i-- // We're gonna re-scan the same mark
} else {
total += mark
}
}
fmt.Println("Average:", float64(total)/float64(n))