Returning boolean when the number is odd or even

Hello! I have written a code where you input a number and if it is even, then it should return true, if odd - false. When I run it, it shows such error:
.\main.go:15:16: not enough arguments to return
have ()
want (bool)
The code:


import "fmt"

func half (x int) bool {
    fmt. Scanf("%f", &x)
    if x % 2 == 0 {
              fmt.Println("The number is even")
	      return true
}
     if x % 2 != 0 {
	       fmt.Println("The number is odd")
	       return false
}
               return
}
func main() {
      fmt. Println("Enter a number: ")
      var x int
      fmt. Println(half)
}      

I copied and pasted the code into play.golang.org and after adding “package main” to the top, the line 15 is in the last line of the half function where it says only return, not saying what it should return.

So how can I make the code work right? If I delete the third return it shows another error:
./prog.go:17:1: missing return at end of function.
I am beginner so I don’t know what I have probably missed.

The compiler doesn’t know that one of the two ifs must be hit. It sees two ifs and needs to know what to return if both of those ifs are false. You could return a default value of false (or true) but, as the code is now, you have to return something.

Another option is, that instead of performing two checks: One to see if x % 2 == 0 and then again later to see if x % 2 != 0, you know that if x % 2 == 0 is false, then x % 2 != 0 will be true, so you could just get rid of that second if:

func half(x int) bool {
	fmt.Scanf("%f", &x)
	if x%2 == 0 {
		fmt.Println("The number is even")
		return true
	}
	fmt.Println("The number is odd")
	return false
}

Thanks. It should work fine. As far as I understood, return should be written inside the function block, so if I have written else { block with return inside it} it would give me another error, because these two returns were written in, so to say, subblocks.
But there is another question about the declaration of the variable. When I tried this code, it has given another error that x was declared but not used. I have declared it in the main function according to another example given in a book I use to study Go language. I thought if I declare the variable in the main function then the function half would expectedly use it even though function half was written before function main.

As I understood with the variable, it may be declared either before function half or inside the block of main function. Then in the main function I should write
fmt.Println(half(x)).
When I do any of these two ways and run the code, it always gives me, whatever number I enter.

The number is even
 True 

So here is the question: How to write it so that the input function will work right?

What book are you using to study Go?

Have you taken A Tour of Go?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.