|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 苏丛 于 2018-5-13 16:37 编辑
题目是这样的:测试密码输入,用静态变量记录输入密码的次数,若连续3次出入错误,显示错误信息并结束程序。
- #include<iostream>
- using namespace std;
- int password(const int & key);
- int main(){
- if(password(123456)) {//123456是正确的密码
- cout<<"Welcome!"<<endl;
- }
- else cout<<"Sorry, you are wrong!"<<endl;
- }
- int password(const int & key){
- static int n = 0;
- int k;
- cout<<"Please input your password";
- cin>>k;
- n++;
- if(n < 3)
- if(k == key) {
- return 1;
- }
- else password(key);
- else
- if(k != key) return 0;
- }
复制代码
我的问题是:
1. 如果第3次才输对的话,返回什么的值是什么?
2. 为什么我在测试的时候把函数改成这样(最后多了一行代码)
- int password(const int & key){
- static int n = 0;
- int k;
- cout<<"Please input your password";
- cin>>k;
- n++;
- if(n < 3)
- if(k == key) {
- return 1;
- }
- else password(key);
- else
- if(k != key) return 0;
- cout<<"test";
- }
复制代码
输错3次也是“welcome”?
3.
如果3次都输错的话,为什么返回给main函数的是0?
求大佬解答
求大神教我
- int password(const int & key){
- static int n = 0;
- int k;
- cout<<"Please input your password";
- cin>>k;
- n++;
- if(n < 3)
- if(k == key) {
- return 1;
- }
- else password(key);
- else
- if(k != key) return 0;
- cout<<"test"; // 以x86为例,没return的都会走到这里,然后寄存器eax就是cout<<"test"的返回值,然后这个eax就当成password的返回值了
- }
复制代码
没必要纠结这种问题,还不如把代码改的没有歧义
- #include<iostream>
- using namespace std;
- int password(const int & key);
- int main() {
- if (password(123456)) {//123456是正确的密码
- cout<<"Welcome!"<<endl;
- } else {
- cout<<"Sorry, you are wrong!"<<endl;
- }
- return 0; // 加个返回值
- }
- int password(const int & key) {
- static int n = 0;
- int k;
- if (n++ < 3) {
- cout << "Please input your password";
- cin >> k;
- cout << n << endl;
- if(k == key) {
- return 1;
- } else {
- return password(key);
- }
- }
- return 0; // 所有分支都要返回值,别让程序不可控
- }
复制代码
|
|