doushao1087 2018-01-31 00:53
浏览 84
已采纳

用Scanf进行偶数和奇数golang打印

package main 
import "fmt"
func main(){
  fmt.Println("Enter a number: ")
  var i int32
  fmt.Scanf("f",%i)
  output := i*1
  if output%2 == 0{
    fmt.Print("even")
}else {
  fmt.Println("odd")
}
}

This is my current code. I am trying to print even and odd number based on using the Scanf but this only print out 'Even'.

  • 写回答

1条回答 默认 最新

  • dongqiang5541 2018-01-31 01:03
    关注

    fmt.Scanf (docs) takes a format string as the first argument. You are providing "f" which is invalid. If you read and reacted to the error returned then you would see the error "input does not match format". This is a working example doing what I believe you originally intended:

    package main
    
    import "fmt"
    
    func main() {
        fmt.Printf("Enter a number: ")
        var i int32
        _, err := fmt.Scanf("%d", &i)
        if err != nil {
            fmt.Printf("%v
    ", err)
            // maybe a good time to exit
        }
        if i%2 == 0 {
            fmt.Print("even")
        } else {
            fmt.Println("odd")
        }
    }
    

    The reason you were always getting "even" is because i was always equal to 0, and zero is even.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100