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