问题出在对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助手提供,问题来源于学员提问