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

C程序无法读取字符且units变量始终返回0的问题求助

问题解决

问题1:无法读取方向字符,程序直接结束

原因是前面用scanf("%d")读取整数后,输入缓冲区里残留了换行符,后续的scanf("%c")会直接读取这个换行符,导致direction的值为换行('\n'),switch语句没有匹配的case分支,程序直接执行完毕,看起来像是没读取字符就结束了。

解决方法:在读取方向的scanf格式串前添加空格,跳过缓冲区里的空白字符(包括换行、空格、制表符):

scanf(" %c",&direction);

也可以用getchar()提前清空缓冲区里的换行符:

getchar(); // 吃掉前面输入留下的换行符
scanf("%c",&direction);

问题2:units变量看起来始终为0

你的代码里没有任何输出units或最终结果的语句,所以无法看到units的实际值,误以为它是0。在代码末尾添加打印语句即可验证:

printf("最终坐标:x=%d, y=%d,移动单位数:%d\n", x, y, units);

另外,switch语句中case 'S'分支缺少break;,属于不良编码习惯,建议补上;同时可以增加default分支处理非法方向输入。

修改后的完整代码:

#include<stdio.h>

int main()
{
    int x,y,units,n;
    char direction;
    printf("enter the co-ordinates [x] [y]:");
    scanf("%d %d" , &x,&y);
    printf("Enter No. units towards:");
    scanf("%d",&units);
    printf("Enter the [direction]:");
    // 加空格跳过空白字符
    scanf(" %c",&direction);

    switch(direction)
    {
        case 'N':
            y=y+units;
            break;

        case 'S':
            y=y-units;
            break; // 补上break
        default:
            printf("无效的方向输入\n"); // 处理非法输入
    }
    // 添加输出语句
    printf("最终坐标:(%d, %d),移动单位数:%d\n", x, y, units);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:41:41