#include<iostream>
using namespace std;
int password(const int &);
int main()
{
if (password(123456))
cout << "Welcome!" << endl;
else cout << "Sorry!You are wrong!Please try again in 5 minutes!" << endl;
system("pause");
}
int password(const int& key)
{
static int n;
int code; ++n;
cout << "Please input the code" << endl;
cin >> code;
if (n <5)
{
if (code == key) return 1;
else cout << "Sorry!You are wrong!Please try again" << endl;
password(key);
}
else
if(code!=key) return 0;
}
这是教材上的例子,我有几点感到非常好奇。第一就是if(code!=key) return 0这句话,这句话貌似起到了非常大的作用,如果删去的话程序运行到第五次输入就会出问题,前四次都输错了,如果第五次输入还是错的,系统会判断为对的
password方法一共三种情况,一是输入正确,返回1,二是输入错误且不超过五次,继续输入,三是输入错误且超过五次,返回0,return 0的那句就是用于第三种情况的,不是可有可无的
n<5和n<=5相比,当n=5时前者不满足,后者满足,后者循环次数就比前者多一次,肯定是不一样的