模板函数练习

题目:试编写一个模板函数Input,它要求用户输入一个非负数,并负责验证用户所输入的数是否真的大于或等于0,如果不是,它将告诉用户该输入非法,需要重新输入一个数。在该函数成功退出之前,应给用户三次机会。如果输入成功,函数应当把所输入的s数作为引用参数返回。输入成功时,函数应返回true,否则返回false

VS2013 下的解答:
#include<iostream>
using namespace std;
template<class T>
bool Input(T &a)
{
int max_count = 3;
cout << "Please input a number a:(a>=0)\n";
for (int i = 0; i < max_count; i++)
{
cin >> a;
if (a >= 0)
return true;
else
cout << "It's not right\n";
}
return false;
}
int main(){
double a;
if (Input(a))
cout << "The number is: " << a << endl;
else
cout << "It's not right,please run the program again!";
return 0;
}








3.试编写一个非递归函数来计算n!.
#include<iostream>
using namespace std;
template <class T>
T Multipn(T n)
{
int s=1;
for (int i = 1; i < n+1; i++)
{
s*=i;
}
return s;
}
int main()
{
int m;
cout << "Please input the number:" << endl;
cin >> m;
int a = Multipn(m);
cout << "The result is " << a<<endl;
return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值