C++ Primer答案 第六章 函数
6.4 编写一个与用户交互的函数,要求输入一个数字,计算生成该数字的阶乘
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int multify(int )
{
int x;
while (cin>>x)
{
int ret=1;
while (x>1)
{
ret *= x--;
}
return ret;
}
}
int main()
{
cout<<multify(3);
}
6.5 编写函数输出其实参的绝对值
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
float absolute(float x)
{
if (x>=0)
return x;
else
return -x;
}
int main()
{
cout<<absolute(-3.14);
}
6.10
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void exc(int *a,int *b)
{
int c=*a;
*a=*b;
*b=c;
}
int main()
{
int m=3,n=4;
int *a=&m;
int *b=&n;
exc(a,b);
cout<<*a<<" "<<*b;
}
6.11
void exc(int &a,int &b)
{
int c=a;
a=b;
b=c;
}
int main()
{
int m=3,n=4;
exc(m,n);
cout<<m<<" "<<n;
}
6.16
bool have_up(const string s)
{
bool a=false;
for (auto &c:s)
{
if (isupper(c))
a = true;
}
return a;
}
string up2low(string s)
{
for (auto &c:s)
{
if (isupper(c))
c=tolower(c);
}
return s;
}
int main()
{
cout<<have_up("hello")<<endl;
cout<<up2low("HEllO");
}
}
6.21
int comp(int a,int *b)
{
if (a>*b)
return a;
else
return *b;
}
int main()
{
int b=5;
cout<<comp(4,&b);
}
6.22
void exc(int *&a,int *&b)
{
int *c=a;
a=b;
b=c;
}
int main()
{
int a=4,b=5;
int *m=&a;
int *n=&b;
exc(m,n);
cout<<*m<<" "<<*n;
}
6.25
int main(int argc,char **argv)
{
string str;
for (int i;i!=argc;++i)
{
str+=argv[i];
str+=" ";
}
cout<<str<<endl;
return 0;
}
6.27
int sum(initializer_list<int> v)
{
int i=0;
for (const auto c:v)
i+=c;
return i;
}
int main()
{
initializer_list<int> v={1,2,3,4,5,6};
cout<<sum(v);
}
6.33
void output(vector<int> v,int ix)
{
if (ix!=v.size())
{
cout<<v[ix++]<<endl;
output(v,ix);
}
}
int main()
{
vector<int> v={5,4,3,2,1};
output(v,0);
}
6.38
int odd[]={1,3,5,7,9};
int even[]={0,2,4,6,8};
decltype(odd) &arrPtr(int i)
{
return (i%2) ? odd :even;
}
int main()
{
for (auto c:arrPtr(2))
cout<<c<<" ";
}
6.42
string make_plural(size_t ctr,const string &word,const string &ending="s")
{
return (ctr>1)?word+ending:word;
}
int main()
{
cout<<make_plural(1,"success")<<endl;
cout<<make_plural(2,"failure")<<endl;
}
6.47
void output(vector<int> v,int ix)
{
if (ix!=v.size())
{
#ifndef NDEBUG
cout<<"第"<<ix+1<<"个数"<<endl;
#endif
cout<<v[ix++]<<endl;
output(v,ix);
}
}
int main()
{
vector<int> v={1,2,3,4,5};
output(v,0);
}
6.55 6.56
int sum(int a,int b)
{
return a+b;
}
int subtract(int a,int b)
{
return a-b;
}
int multify(int a,int b)
{
return a*b;
}
int divide(int a,int b)
{
return (b!=0) ? a/b :0;
}
int main()
{
typedef int(*p) (int a,int b);
vector<p> v{sum,subtract,multify,divide};
for (auto c:v)
cout<<c(1,0)<<endl;
}
|