.                   
计算机程序设计(c++)6周编程作业
1
递归猴子摘桃(20分)
题目内容:
猴子摘桃:一天,一只猴子摘了若干桃子,当天吃掉一半,觉得不过瘾,又吃了一个;第二天将剩下的桃子吃掉一半又多吃了一个;…,每天将前一天剩下的桃子吃掉一半又多吃一个,直到第n天,发现只剩下一个桃子,问第一天它摘了多少桃子。
编写递归函数,计算第一天猴子摘的桃子的数量。在主函数中输入n,调用函数计算第一天摘的桃子的数量,在主函数中输出。
输入:剩下一只桃子的天数n,n>=1。
输出:第一天摘的桃子数量。
【提示】函数格式:int  monkeyandPeak(int k,int n),其中n1只桃子的天数,k是求哪天的桃子数,返回是第k天的桃子数。主函数的调用格式:
    count= monkeyandPeak(1,n);  //n天只剩1只桃,求第1天的桃子数
【注意】使用递归实现。
样例1输入:
10
样例1输出:
1534
#include<stdio.h>
# include <iostream>
using namespace std;
int peach(int n)
//N天只剩下一个桃子了
{
if(n==1)return 1; c编程必背100题
return 2*(peach(n-1)+1);
}
int main()
{
int a;
cin>>a;
printf(%d\n,peach(a));
return 0;
}
9
/ 1
                        .                   
2
编写内联函数求矩形的面积和周长(20分)
题目内容:
编写函数求矩形的面积和周长,由于算式非常简单,请使用内联函数方式编写,提高程序运行效率
输入格式:
矩形的长和宽,均为整数
输出格式:
矩形的面积和周长
输入样例:
3 5
输出样例:
15 16
# include <iostream>
using namespace std;
inline int GetSize(int a, int b){ 
  int size = a*b;
  return size;
}
inline int GetPerimeter(int a, int b){ 
  int perimeter = 2*(a+b);
  return perimeter;
}
int main(){
  //---define---
  int a,b;
  //---input---
  cin>>a;
  cin>>b;
  //---execute---
  //---output---
  cout<<GetSize(a,b)<< ;
  cout<<GetPerimeter(a,b)<<endl;
  return 0;
}
9
/ 2
                        .                   
3
编写重载函数显示字符串(20分)
题目内容:
编写函数 print_spaced 显示字符串,要求显示出的字符串每个字母之间都有一个空格。要求编写两个同名函数,一个支持字符数组输入,另一个支持string类型输入。然后编写main函数测试这两个函数,第一个使用字符数组输入,第二个使用string类型输入。
输入格式:
两个字符串,长度不超过100,只包含英文大小写字母,不含其他字符。
输出格式:
经间隔空格处理后的两个字符串,两个字符串分居两行。注意字符串的最后一个字母后面没有空格。
输入样例:
news
final
输出样例:
n e w s
f i n a l
# include <iostream>
# include <cstring>
using namespace std;
void print_spaced(char word[], int length){
  int i;
  cout<<word[0];
  if(length>1){
    for(i=1;i<length;i++) cout<< <<word[i]; 
  }
}
void print_spaced(string xword, int count){
  int i;
  int pos = 1;
  if(count>1){ 
  for(i=1;i<count;i++){
    xword.insert(pos, );
    pos = pos + 2;
9
/ 3
                        .                   
  }
  }
  cout<<xword;
}
int main()
{
  //---define---
  int i,length = 0,strlen;
  char word[100];
  string xword;
  //---input---
  line(word,100);
  getline(cin,xword);
  //---execute---
  for(i=0;word[i]!='\0';i++)  length++;
  print_spaced(word, length);
  cout<<endl;
  strlen = xword.length(); 
  print_spaced(xword, strlen);
  //---output---
  return 0;
}
4
排序函数重载(20分)
题目内容:
编写一组重载的排序函数,可以对两个整数、三个整数、四个整数、整数数组从大到小排序,函数名为sort,其中数组排序应使用递归的方法,另补充print函数,在一行显示排序后的数组元素。