go - Golang- invalid array bound -


when run code below error:

school_mark.go:8: invalid array bound s 

my code:

package main  import "fmt"  func main(){    var subj float64    fmt.println("enter how have subjects inn school: ")    fmt.scanf("%f", &subj)    s := subj    var mark [s]float64    var float64    = 0; a<s; a++{      fmt.scanf("%f", &mark)    }    var total float64    var float64    i= 0; i<subj; i++{        total += mark[i]    }        fmt.println(total/subj)     } 

what problem?

spec: array types:

the length part of array's type; must evaluate non-negative constant representable value of type int.

your length in [s]float64 not constant.

use slice instead of array type, , know have use integer type length, e.g.:

var mark []float64 = make([]float64, int(s)) 

or short:

mark := make([]float64, int(s)) 

going forward, use integer types (e.g. int) indices. can declare in for like:

for := 0; < len(mark); i++ {     fmt.scanf("%f", &mark[i]) } 

or can use for ... range range on indices of slice:

for := range mark {     fmt.scanf("%f", &mark[i]) } 

i use int type everywhere: number of subjects , marks not have meaning if non integers.

also fmt.scanf() not consume newline, subsequent fmt.scanf() call return error.

you should check errors or parsed values, both returned fmt.scan*() functions.

also don't have loop slice twice, can calculate total (the sum) in first.

going more forward, don't have store marks in slice, ask entered number of marks, calculate sum on fly , print average.

something this:

var n, total, mark int fmt.println("number of subjects:") fmt.scanln(&n) := 0; < n; i++ {     fmt.scanln(&mark)     total += mark } fmt.println("average:", float64(total)/float64(n)) 

if add required checks, 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 } := 0; < 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 again!")         fmt.scanln()         i-- // we're gonna re-scan same mark     } else {         total += mark     } } fmt.println("average:", float64(total)/float64(n)) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -