C++ prime plus 第八章 函数探幽 习题



1、接收字符串,根据被调用次数打印字符串

# include<iostream>
# include<string>
using namespace std;

void fun(string tr,int & c,int num=0)//默认参数的设置必须在参数列表的最右端
{
 c++;
 for(int i=0; i<c; i++)
  cout<<tr<<endl;
 return;
}

int main(void)
{
 string str="haha";
 int c = 0;//计数fun()被调次数,初始为零
 fun(str,c,1);
 fun(str,c,1);//
 return 0;
}

2、默认参数的设置

# include<iostream>
# include<string>
using namespace std;

struct CandyBar
{
 char * name;
 double weight;
 int heat;
};

void fun(CandyBar & brand,char * nam ="Millennium",const double wei =2.85,const int hea = 350)
{
 brand.name = nam;
 brand.weight = wei;
 brand.heat = hea;
 cout<<brand.name<<"\t"<<brand.weight<<"\t"<<brand.heat<<endl;
 return ;
}

int main(void)
{
 CandyBar a;
 fun(a,"haha",2.1,3);
 return 0;
}

3、小写转换成大写(toupper)

<pre class="cpp" name="code"># include<iostream>
# include<string>
# include<cctype>
using namespace std;

void fun(string & a)
{
	for(int i=0; i<a.size(); i++) //string 类定义的字符串是没有‘\0’结束标志的
	{
		a[i] = toupper(a[i]); //toupper是定义在头文件cctype中的小写字母转大写字母的函数
	}
	return ;
}

int main(void)
{
	string str;
	cin>>str;
	string temp;
	fun(str);
	cout<<str<<endl;
	while(1)
	{
		cout<<"Next string (q to quit):"<<endl;
		cin>>temp;
		if(temp == "q")
		{
			cout<<"Bye"<<endl;
			break;
		}
		else
		{
			fun(temp);
			cout<<temp<<endl;
		}
	}
	return 0;
}
4、
# include<iostream>
using namespace std;
# include<cstring>

struct stringy
{
	char * str;
	int ct;
};

void set(stringy & b, char *);
void show(const stringy b , int n =1);
void show(const char * t, int n=1);

int main()
{
	stringy beany;
	char testing[]="Reality isn't what it used to be.";
	set(beany,testing);
	show(beany);
	show(beany,2);
	testing[0]='D';
	testing[1]='u';
	show(testing);
	show(testing,3);
	show("Done!");
	return 0;
}

void set(stringy & b, char * t)
{
	b.str = new char [strlen(t)];
	b.str = t;
	b.ct = strlen(t);
	return ;
}


void show(stringy b,int n)
{
	for(int i=0; i<n; i++)
	{
		cout<<b.str<<endl;
	}
	return ;
}

void show(const char * t,int n)
{
	for(int i=0; i<n; i++)
	{
		cout<<t<<endl;
	}
	return ;
}

5、模版函数
# include <iostream>
using namespace std;

template <typename T> 
T max5(T a[]);

int main()
{
	int a1[5] = {1,2,3,4,5};
	double a2[5] = {1.1,2.2,3.3,4.4,5.5};
	cout<<"int类型最大值:"<<max5(a1)<<endl;
	cout<<"double类型最大值:"<<max5(a2)<<endl;
	return 0;
}

template <typename T>
T max5(T a[])
{
	T max;
	max =a[0];
	for(int i=1; i<5; i++)
	{
		if(max<a[i])
			max=a[i];
		else
			;
	}
	return max;
}

6、

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值