首页 > 解决方案 > 即使条件不满足 C++ 也无限循环

问题描述

当第一次不满足while条件(有效性为假)时,代码正常运行并打印“有效”。

但是,当满足 while 条件(有效性为真)然后它变得不满足时,它不会退出循环。它变成了一个无限循环,打印“无效,请重试”。和“输入卡号”一遍又一遍。

我真的不知道我的代码有什么问题。

先感谢您。

代码:

#include <iostream>

using namespace std;

//count the number of digits
int numdig(int digits)
{
    int count = 0;
    while (digits != 0)
    {
        digits = digits / 10;
        ++count;
    }
    return count;
}
//valid length or not
bool validity(int len){
    bool notValid;
    if(len<14 or len>16){
        notValid = 1;
    }
    else{
        notValid = 0;
    }
    return notValid;
}


int main()
{
    int digits;
    cout<<"Enter CN: ";
    cin>>digits;
    cout<<numdig(digits)<< endl;
    cout<<validity(numdig(digits))<<endl;

    while(validity(numdig(digits))){
        cout<<"Not valid, please try again."<<endl;
        cout<<"Enter card number "<<endl;
        cin>>digits;
        validity(numdig(digits));
    }

    cout<<"Valid";

    return 0;
}

标签: c++loopswhile-loop

解决方案


推荐阅读