dqa35710 2016-01-27 07:49 采纳率: 0%
浏览 66

Golang-无效的数组绑定

When I run the code below I get the error:

school_mark.go:8: invalid array bound s

My code:

package main

import "fmt"

func main(){
   var subj float64
   fmt.Println("Enter how much you have subjects inn school: ")
   fmt.Scanf("%f", &subj)
   s := subj
   var mark [s]float64
   var a float64
   for a = 0; a<s; a++{
     fmt.Scanf("%f", &mark)
   }
   var total float64
   var i float64
   for i= 0; i<subj; i++{
       total += mark[i]
   }
       fmt.Println(total/subj)    
}

What is the problem?

  • 写回答

1条回答 默认 最新

  • doushang7209 2016-01-27 07:55
    关注

    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))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)