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

问题出在函数get_english()中对于num1、num2、num3数组的定义。这些数组的元素类型应为字符串常量指针(const char*),而不是字符指针(char*)。另外,在给str赋值之前,需要先将其清空。以下是修正后的代码:

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

#define MAXSIZE 100

const char* get_english(int n);

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

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

const 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; 
    
    static char str[MAXSIZE] = {0}; 
    int index = 0;

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

   return strdup(str);   
}

这样修改后,应该能够正确输出整数的英文描述。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?