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

如何正确使用strcmp匹配多字符串?C语言代码判断逻辑问题排查

解决strcmp判断输入逻辑错误的问题

你的代码核心计算功能正常,但开头的yes/no判断逻辑存在问题:无论输入什么内容,程序都会进入计算流程。这是因为你错误使用了strcmp的返回值逻辑。

错误原因

strcmp函数的返回规则是:

  • 当两个字符串相等时,返回0
  • 当两个字符串不相等时,返回非0值(正数或负数)

你原代码中的判断条件:

if (strcmp(answer, "y") || strcmp(answer, "Y") || strcmp(answer, "yes"))

逻辑完全错误:只要输入的字符串不等于其中任意一个,对应的strcmp就会返回非0,||逻辑或只要有一个非0就会让整个条件为真。而输入不可能同时等于"y""Y""yes"三个值,所以这个条件永远为真,导致所有输入都会进入计算分支。

修正方案

方案一:正确判断strcmp的返回值

将每个strcmp的判断改为检查返回值是否为0,用||连接(满足任意一个匹配即可):

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

void calculate(int number);

int main(void)
{
    char answer[20];
    printf("Type yes or no (y/n) if you want to have the sum of the digits; ");
    scanf("%s", answer);

    // 修正后的判断逻辑:匹配任意一个合法输入则进入计算
    if (strcmp(answer, "y") == 0 || strcmp(answer, "Y") == 0 || strcmp(answer, "yes") == 0)
    {
        int number = get_int("Write your number here: ");
        calculate(number);
        return 0;
    }
    else
    {
        printf("bye\n");
        return 1;
    }
}

void calculate(int n)
{
    int c = 0, sum = 0, r;
    do
    {
        sum = n;
        while (n != 0)
        {
            r = n % 10;
            sum = sum + r;
            n = n/10;
        }
        n = sum;
        printf("Sum of the digits of your number = %d\n", sum);
        c++;
    } while (sum < 1000);
    printf("Number of calculations %d\n", c);
}

方案二:统一转换为小写再判断(优化版)

可以先把输入的字符串全部转成小写,减少判断分支,让代码更简洁:

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

void calculate(int number);
void to_lower(char *str); // 新增转小写函数

int main(void)
{
    char answer[20];
    printf("Type yes or no (y/n) if you want to have the sum of the digits; ");
    scanf("%s", answer);

    to_lower(answer); // 转成小写
    if (strcmp(answer, "y") == 0 || strcmp(answer, "yes") == 0)
    {
        int number = get_int("Write your number here: ");
        calculate(number);
        return 0;
    }
    else
    {
        printf("bye\n");
        return 1;
    }
}

void to_lower(char *str)
{
    for (int i = 0; str[i] != '\0'; i++)
    {
        str[i] = tolower((unsigned char)str[i]);
    }
}

void calculate(int n)
{
    int c = 0, sum = 0, r;
    do
    {
        sum = n;
        while (n != 0)
        {
            r = n % 10;
            sum = sum + r;
            n = n/10;
        }
        n = sum;
        printf("Sum of the digits of your number = %d\n", sum);
        c++;
    } while (sum < 1000);
    printf("Number of calculations %d\n", c);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:15:40