如何解决在这种情况下如何添加计数器?
编程新手。我编写了一个简单的程序,读取了银行密码,但是却遇到了无限循环。我知道我应该添加一个计数器,因为那是我的老师说的,但是我不知道如何实际实现它。如果有人可以帮助,那就太好了。
#include <iostream>
using namespace std;
int main() {
int pin = 12345;
int input;
cout << "Please enter your pin." << endl;
cin >> input;
while (input != 12345) {
cout << "INCORRECT PIN. TRY AGAIN." << endl;
cout << "Please enter your pin." << endl;
}
else if (input==12345) {
cout << "ACCESS GRANTED. WELCOME TO YOUR BANK" << endl;
}
return 0;
}
解决方法
您不会在while循环中再次输入。这就是它运行无限循环的原因。 试试这个
int main() {
int pin = 12345;
int input;
cout << "Please enter your pin." << endl;
cin >> input;
while (input != pin) {
cout << "INCORRECT PIN. TRY AGAIN." << endl;
cout << "Please enter your pin." << endl;
cin >> input;
}
if (input==pin) {
cout << "ACCESS GRANTED. WELCOME TO YOUR BANK" << endl;
}
return 0;
}
如果您想要计数器,例如用户输入错误的密码超过3次,则不应让他访问银行帐户。
int main() {
int pin = 12345;
int input;
const int times = 3;
int counter = 0;
do{
cout << "Please enter your pin." << endl;
cin >> input;
if(input != pin){
cout << "INCORRECT PIN. TRY AGAIN." << endl;
counter++;
} else {
break;
}
if(counter == times){
cout << "You cannot access your account. You enter wrong pin for 3 times\n";
return 0;
}
}while(input != pin);
if (input==pin) {
cout << "ACCESS GRANTED. WELCOME TO YOUR BANK" << endl;
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。