Solve the problem (Golang Programming classic case) monkey eating peaches with Go language

Problem : There are a bunch of peaches, the first day of the monkeys ate half of them, and eat one. After the monkeys eat half of it every day, then eat a, when the first 10 days, and found that only a peach. Question: How many peaches initial total.

Analysis of ideas :

  1. Day 10 only a peach;
  2. 9th day = number of peaches (peach day 10 the number of + 1) *;
  3. Law: n-number of days Peach: peach (n) = (peach (n + 1) + 1) * 2

code show as below:

package main

import "fmt"

func peach(n int) int{
	if n>10 || n<1 {
		fmt.Println("输入的天数不对")
		return 0
	} else if n==10 {
		return 1
	} else {
		return (peach(n+1)+1)*2
	}
}

func main() {
	fmt.Print("请输入天数:")
	var n int
	fmt.Scan(&n)
	fmt.Printf("第%v天桃子的数量是:%v",n,peach(n))
}

Execution results as shown below:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/93377813