dongruidian3064 2013-10-09 16:23
浏览 14
已采纳

golang中的if else语句

Could someone help me debug this program, only the else part is processed on every input. This id a program for grading students. a student inputs a mark and the the grade is displayed

func main(){
    var x int
    fmt.Println("Enter your marks")

    fmt.Scanf("%d",&x)

    if (100 <= x) && (x<=75){
        fmt.Println("D1")
    }else if (74 <= x)&&(x <= 70){
        fmt.Println("D2")
    }else if (69 <= x )&&(x<=65){
        fmt.Println("C3")
    }else if (64 <= x)&&(x <= 60){
        fmt.Println("C4")
    }else if (59 <= x)&&(x <= 55){
        fmt.Println("C5")
    }else if (54 <= x)&&( x<= 50){
        fmt.Println("C6")
    }else if (49 <= x )&&(x<= 45){
        fmt.Println("P7")
    }else{
        fmt.Println("Work harder")
    }
}
  • 写回答

4条回答 默认 最新

  • douguwo2275 2013-10-09 16:25
    关注

    You have a logic problem.

    Change

    if (100 <= x) && (x<=75){
    

    to

    if 75 <= x && x <= 100 { // numbers here are ordered from smallest to greatest
    

    because a number can't be greater than 100 and smaller than 75.

    And it's the same for the other lines of course.

    Note that you could make less comparisons. Suppose you test if the number is smaller than 100 initially, then you don't have to test if it's smaller than 75 just after you tested it's smaller than 75.

    A typical Go code would probably have a switch here instead of all those if/else. See switch in the documentation. Here's how it could be written with a switch :

    switch {
    case x > 100:
        fmt.Println("Congrats!") // you forgot this one
    case x >= 75:
        fmt.Println("D1")
    case x >= 70:
        fmt.Println("D2")
    case x >= 65:
        fmt.Println("C3")
    case x >= 60:
        fmt.Println("C4")
    case x >= 55:
        fmt.Println("C5")
    case x >= 50:
        fmt.Println("C6")
    case x >= 45:
        fmt.Println("P7")
    default:
        fmt.Println("Work harder")
    }
    

    A last comment : This type of switching code rarely occurs because normally the thresholds and related notes are stored as data, for example in a struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗