You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50第二周密码验证bool函数始终返回TRUE,求问题排查

问题分析与修复

你的代码核心逻辑错误在于用累加符合条件的字符次数来判断密码是否满足要求,而不是检查密码是否同时包含四类字符(大写、小写、标点、数字)。具体问题如下:

  • 当前逻辑中,只要validation的数值等于4就返回true,但这个数值可能是同一类型字符重复出现4次(比如输入四个大写字母,validation会累加为4),此时密码并不满足四类字符都存在的要求,但函数错误返回true。
  • 反之,如果密码包含所有四类字符但长度超过4,validation会大于4,函数会错误返回false。

修复方案

正确的思路是用四个布尔变量分别标记四类字符是否存在,遍历密码时只要遇到对应类型的字符,就将对应标记设为true(只需标记一次,无需重复累加),最后判断四个标记是否全部为true。

修正后的代码:

#include <cs50.h>
#include <string.h>
#include <ctype.h>

bool valid(string password)
{
    bool has_upper = false;
    bool has_lower = false;
    bool has_punct = false;
    bool has_digit = false;

    for (int n = 0; n < strlen(password); n++)
    {
        if (isupper(password[n]))
        {
            has_upper = true;
        }
        else if (islower(password[n]))
        {
            has_lower = true;
        }
        else if (ispunct(password[n]))
        {
            has_punct = true;
        }
        else if (isdigit(password[n]))
        {
            has_digit = true;
        }
        // 提前判断:如果四个条件都满足了,直接跳出循环节省资源
        if (has_upper && has_lower && has_punct && has_digit)
        {
            break;
        }
    }

    return has_upper && has_lower && has_punct && has_digit;
}

关键改进点

  • 用四个布尔变量分别追踪四类字符的存在性,确保每类至少出现一次。
  • 使用else if避免重复判断(一个字符只会属于一种类型),提升代码效率。
  • 增加提前跳出循环的逻辑,当四类字符都已找到时,无需继续遍历剩余字符。

内容的提问来源于stack exchange,提问作者OldLadyCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:46:18