小编esa*_*sam的帖子

通过递归达到数字42

我正在尝试创建一个用户输入数字(n)的熊游戏,程序将通过执行一些指定的步骤来查看它是否可以达到数字42.如果不能,则通知用户该号码无法达到目标.

这些是规则:

  1. 如果n是偶数,那么你可以准确地回馈n/2个熊.
  2. 如果n可以被3或4整除,那么你可以将n的最后两位数相乘并返回这么多熊.
  3. 如果n可以被5整除,那么你可以回馈42个熊.

这是一个例子:

  • 从250头开始
  • 由于250可以被5整除,你可以返回42只熊,留下208只熊.
  • 由于208是偶数,你可以返回一半的熊,留下104只熊.
  • 由于104是偶数,你可以返回一半的熊,留下52只熊.
  • 由于52可被4整除,因此您可以将最后两位数乘以(得到10)并返回这10个熊.这让你有42只熊.
  • 你已达到目标!

这是我到目前为止所拥有的:

#include <iostream>

using namespace std;

bool bears(int n);

int main(){
    int number;

    do{
        cout<<"enter the amount of bears (press 0 to stop the program): ";
        cin>>number;
        if (bears(number)){
            cout<<"you have reached the goal!"<<endl;
        }

        else{
            cout<<"sorry, you have not reached the goal."<<endl;
        }

    }while(number != 0);
}

bool bears(int n){
    if (n < 42){
        return false;
    }

    else if (n == 42){
        return true;
    }

    else{
        if …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm recursion

2
推荐指数
1
解决办法
955
查看次数

标签 统计

algorithm ×1

c++ ×1

recursion ×1