问题说明:
房间内有一只猴子,一个箱子和一个挂在天花板上的香蕉。三者的位置如下图所示:
初始状态:三者在输入的初始位置,猴子手上无香蕉,猴子不在箱子上。
目标状态:三者均在香蕉对应的位置,猴子手上有香蕉,且在箱子上。
实现步骤:猴子走到箱子处猴子将箱子推到香蕉处猴子爬上箱子猴子摘香蕉
程序内容: 本程序主要实现猴子摘香蕉的过程,即从初始状态到目标状态。程序运行后,根据用户输入 的三者的位置,按照实现步骤更新每一过程后的状态变量,并将过程输出。
本程序使用以下函数:
main():主函数
go_to_box():猴子走到箱子处
move_box():猴子搬箱子
climb_box():猴子爬箱子
get_banana():猴子摘香蕉
本程序使用C++实现:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
File name:monkey_get_banana
Date:11.15
*/
//用一个结构体变量记录某一状态下猴子、箱子、香蕉的位置,以及猴子是否在箱子上、是否摘得香蕉
struct stack{
string MONKEY;
string BANANA;
string BOX;
int HAVE; //1表示摘得,0表示没有
int ISON; //1表示猴子在箱子上,0表示没有
};
//函数申明
bool go_to_box(struct stack& s,string m,string n);
bool move_box(struct stack& s, string m, string n);
bool climb_box(struct stack& s, string pos);
bool get_banana(struct stack& s,string pos);
int main(){
string monkey,banana,box;
struct stack sq;
cout << "用a,b,c三个数字输入猴子、香蕉、箱子的位置,中间用空格隔开" << endl;
cin >>monkey>>banana>>box;
cout <<"输入的 猴子 香蕉 箱子的位置分别是:"<<endl;
cout <<"monkey\tbanana\tbox"<<endl;
cout <<monkey<<"\n\t"<<banana<<"\n\t\t"<<box<<endl;
cout <<"猴子摘香蕉的过程如下:"<< endl;
//初始化
sq.MONKEY = monkey;
sq.BANANA = banana;
sq.BOX = box;
sq.HAVE = 0;
sq.ISON = 0;
//摘香蕉过程
go_to_box(sq,sq.MONKEY,sq.BOX);
move_box(sq, sq.MONKEY, sq.BANANA);
climb_box(sq,sq.BANANA);
get_banana(sq,sq.BANANA);
return 0;
}
bool go_to_box(struct stack& s,string m,string n){
if (s.MONKEY == m){
s.MONKEY = n;
cout <<"\n第一步:猴子从 "<<m<<" 处走到 "<<n<< endl;
return true;
}
else
return false;
return true;
}
bool move_box(struct stack& s, string m, string n)
{
if (s.MONKEY == m && s.BOX == m)
{
s.MONKEY = n;
s.BOX = n;
cout <<"\n第二步:猴子将箱子从 "<<m<<" 处移到 "<<n<< endl;
return true;
}
else
return false;
return true;
}
bool climb_box(struct stack& s, string pos){
if (s.MONKEY == pos && s.BOX == pos && s.BANANA == pos && s.ISON == 0)
{
s.ISON = 1;
cout <<"\n第三步:猴子在"<<pos<<"处爬上箱子"<<endl;
return true;
}
else
return false;
return true;
}
bool get_banana(struct stack& s,string pos){
if (s.MONKEY == pos && s.BOX == pos && s.BANANA == pos && s.ISON == 1){
s.HAVE = 1;
cout <<"\n第四步:猴子摘得香蕉"<<endl;
}
else
return false;
return true;
}
程序运行结果:
作业要求完美实现!!!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。