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

C语言输入数字转对应英文单词功能失效问题排查

问题:输入数字无法输出对应英文单词

程序仅能获取用户输入但不输出对应英文单词,例如输入5时预期输出"five",但无任何输出。

原代码

#include<stdio.h>

void main(void)
{
    char *between_[10]={"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    int i;

    for(i=0; i<8; i++)
    {
        if( n == *(between_+i) )
        {
            printf("%s", between_[i]);
        }
    }
}

错误分析

  • 类型不匹配的比较:*(between_+i)是字符串指针(地址值),和整数n比较毫无意义,永远不会相等,这是核心错误。
  • 循环范围不足:数组包含9个元素(对应1-9),原循环i<8只遍历到索引7(对应"eight"),漏掉了索引8的"nine"。
  • 非标准main函数:C标准中main函数应返回int类型,而非void。

修正后的代码

#include<stdio.h>

int main(void)
{
    char *between_[10]={"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    
    // 检查输入是否在1-9范围内
    if(n >=1 && n <=9)
    {
        // 数字n对应数组索引n-1
        printf("%s\n", between_[n-1]);
    }
    else
    {
        printf("请输入1-9之间的整数\n");
    }
    
    return 0;
}

修改说明

  1. 直接通过n-1作为数组索引,无需循环遍历,更高效直观。
  2. 增加输入范围校验,避免非法输入导致数组越界。
  3. 修正main函数返回类型为int,符合C标准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:30:44