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(...

代码中存在一个错误:在定义字符串数组时,应使用字符数组而不是指针数组。以下是修正后的完整代码:

#include <stdio.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);
   
    return 0;
}

char* get_english(int n)
{
    char num1[][10] = {" ", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};  
    char num2[][10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", 
                       "Eighteen","Nineteen"};
    char num3[][10] = {"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; 
    
    static char str[MAXSIZE] = {0}; 
    int index = 0;

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

    
    if (thousands != 0)
        index += sprintf(str + index, "%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)
            index += sprintf(str + index, "%s ", num1[ones]);
    }

    return str;   
}

修正后的代码中,我将指针数组改为了字符数组,并做了相应的调整。此外,还对部分字符串拼接和返回结果进行了优化。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?