题目:试编写一个模板函数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;
}