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

C语言初学者求助:字符输入判断逻辑代码错误排查与修正

苹果购买代码错误排查与修正

存在的问题及修正说明:

  • 字符串存储与输入错误:原代码用char response;存储"Yes/No"这类字符串,单个char仅能容纳一个字符,会引发内存溢出。需改为字符数组char response[4];(足够容纳"Yes"/"No"及字符串结束符),同时scanf输入时直接传入数组名(数组名本身代表首地址),即scanf("%s", response);。

  • 字符串比较错误:C语言中不能用==直接比较字符串,需使用标准库函数strcmp(需包含<string.h>头文件)。判断条件应改为strcmp(response, "Yes") == 0(表示两个字符串相等)和strcmp(response, "No") == 0。

  • 语法与格式错误:

    • printf的换行需用\n转义字符,原代码直接换行的写法不符合C语法规范。
    • 代码末尾存在多余的闭合大括号},导致语法结构错误,需删除。
  • 冗余代码与未使用变量:

    • 判断extraApples的if-else逻辑完全重复,可直接简化为单句输出。
    • totalPrice变量声明后未被使用,示例中补充了基础总价计算逻辑,也可根据需求删除该变量。

修正后的完整代码

#include <stdio.h>
#include <string.h>

int main() {
    int apples = 0;
    int dozenofApples;
    int extraApples;
    int totalPrice;
    char response[4];

    printf("Input amount apples: ");
    scanf("%d", &apples);

    dozenofApples = apples / 12;
    extraApples = apples % 12;

    printf("You have %d dozen apples and %d extra apples", dozenofApples, extraApples);

    // 计算总价(可根据实际定价调整单个苹果价格)
    if (dozenofApples >= 2) {
        totalPrice = dozenofApples * 120 + extraApples * 10;
        printf(" and this will cost you 120 PHP per dozen, total: %d PHP.\n", totalPrice);
    } else {
        totalPrice = dozenofApples * 150 + extraApples * 13;
        printf(" and this will cost you 150 PHP per dozen, total: %d PHP.\n", totalPrice);
    }

    printf("Continue to purchase? Yes/No\n");
    scanf("%s", response);

    if (strcmp(response, "Yes") == 0) {
        printf("Purchase Complete! Come again!\n");
    } else if (strcmp(response, "No") == 0) {
        printf("Purchase cancelled.\n");
    } else {
        printf("Invalid input.\n");
        return 0;
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 07:46:22