ZBLOG

#include #define MAXSIZE 100 char* get_english(int n); int main() { int n = 0; printf("请输入一个非负整数:"); scanf("%d", &n); char* str = get_english(n); printf("该整数的英文描述为:%s", str); return 0; } char* get_english(...

问题出在对num2数组的定义上,它应该是一个一维字符指针数组而不是二维字符指针数组。请将num2的定义修改为以下形式:

const char* num2[MAXSIZE] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};

这样就能够正常输出正确的结果了。完整代码如下:

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

#define MAXSIZE 100

char* get_english(int n);

int main()
{
    int n = 0;
    printf("请输入一个非负整数:");
    scanf("%d", &n);

    char* str = get_english(n);
    printf("该整数的英文描述为:%s\n", str);

    free(str);
   
    return 0;
}

char* get_english(int n)
{
    const char* num1[MAXSIZE] = {" ", "One", "Two", "Three", "Four", "Five", "Six",
                                 "Seven", "Eight","Nine"};  
    const char* num2[MAXSIZE] = {"Ten","Eleven","Twelve","Thirteen","Fourteen",
                                 "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    const char* num3[MAXSIZE] = {"Ten","Twenty","Thirty","Forty",
                                 "Fifty","Sixty","Seventy",
                                 ,"Eighty" ,"Ninety"};

    int thousands = n / 1000; 
    int hundreds = (n % 1000) / 100;
    int tens = (n % 100) / 10;
    int ones = n % 10; 
    
    char* str = malloc(MAXSIZE * sizeof(char));
    int index = 0;

    if (n == 0)
    {
        strcpy(str, "Zero");
        return str;
    }

    str[0] = '\0';
    
    if (thousands != 0)
    {
        index += sprintf(str, "%s Thousand ", num1[thousands]);
    }

    if (hundreds != 0)
    {
        index += sprintf(str + index, "%s Hundred ", num1[hundreds]);
    }

    if (tens == 1)
    {
        index += sprintf(str + index, "%s ", num2[ones]);
    }
    else
    {
        if (tens != 0)
        {
            index += sprintf(str + index, "%s ", num3[tens - 1]);
        }
        
        if (ones != 0 && tens != 0)
        {
            index += sprintf(str + index, "%s ", num1[ones]);
        }
        
       
      
   }
   
   str[index] = '\0';

   return str;   
}

修改后的代码会正确输出整数的英文描述。同时需要注意,在使用strdup()函数前,我们需要先为结果字符串str分配内存空间,并在结束时使用free()函数释放内存。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=2116

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?