主题:求解
huanglulutian
[专家分:0] 发布于 2011-11-13 12:11:00
编写函数int convert_to_chinese( unsigned int x, char *output_buf, int output_buf_size ),将整数x(32-bits)以中文形式输出到outout_buf中,例如“1234567890”,输出为“一十二亿三千四百五十六万七千八百九十”,返回输出字符串的长度
(好多人让我看人民币大小写转换,但是看了也没怎么看懂,求高人帮忙解这个题)
4 楼
laowang [专家分:90] 发布于 2011-11-13 20:21:00
给你写了一个作为你的参考,忠告你,编程要多练习。不要浪费时光呀!你下去自己再优化一下。你说的功能实现了,范围最大为
2147483647 is 二十一亿四千七百四十八万三千六百四十七,你再想法把程序改一下,让它可以支持更大的,让程序效率更高,这是在linux的gcc环境下编译。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define B 100000000
#define M 10000
#define T 1000
#define H 100
#define TEN 10
#define SIZE 100
#define LEN 40
char *digits[10] = {"零","一","二","三","四","五","六","七","八","九"};
char *name[5] = {"亿","万","千","百","十"};
int convert_to_chinese(unsigned int x,char *output_buf,int out_put_buf_size);
void convert(int number,char *str,int size);
int main()
{
char output[SIZE]={'\0'};
unsigned int x;
printf("Input a unsigned integer:");
scanf("%d",&x);
int n = convert_to_chinese(x,output,SIZE);
printf("%d is %s,right?\n",x,output);
return 0;
}
int convert_to_chinese(unsigned int x,char *output_buf,int out_put_buf_size)
{
int bill;
int thou;
int hun;
int mill;
int ten;
int s;
if((bill = x / B) > 0){//可以达到"亿"
char tmp[LEN]={'\0'};
convert(bill,tmp,LEN);
strcat(output_buf,tmp);
strcat(output_buf,name[0]);
x %= B;
}
if((mill = x / M) > 0){//可以达到"万"
char tmp[LEN]={'\0'};
convert(mill,tmp,LEN);
strcat(output_buf,tmp);
strcat(output_buf,name[1]);
x %= M;
}
//可以达到"千",一千以内可以由convert来处理
if(x < 1000){
strcat(output_buf,digits[0]);
char tmp[LEN]={'\0'};
convert(x,tmp,LEN);
strcat(output_buf,tmp);
}else{
char tmp[LEN]={'\0'};
convert(x,tmp,LEN);
strcat(output_buf,tmp);
}
}
void convert(int number,char *str,int size)
{
int tmp;
if(number >= 0 && number < 10)//<10
strcat(str,digits[number]);
else if(number >=10 && number <=99){//10-99
strcat(str,digits[number/10]);
strcat(str,name[4]);
if((tmp= number %10) != 0)
strcat(str,digits[tmp]);
}
else if(number >=100 && number <=999){//100-999
strcat(str,digits[number/100]);
strcat(str,name[3]);
if( (number%100/10) !=0){
strcat(str,digits[number%100/10]);
strcat(str,name[4]);
}
else
strcat(str,digits[0]);
if((tmp = number % 100 % 10) != 0)
strcat(str,digits[tmp]);
}
else if(number >=1000 && number <=9999){//1000-9999
if( (number % 1000) == 0){
strcat(str,digits[number/1000]);
strcat(str,name[2]);//显示"千"
}else{
strcat(str,digits[number/1000]);
strcat(str,name[2]);//显示"千"
if((number%1000/100) != 0){
strcat(str,digits[number%1000/100]);
strcat(str,name[3]);//显示"百"
}
else
strcat(str,digits[0]);
if((number%1000%100/10) != 0){
strcat(str,digits[number%1000%100/10]);
strcat(str,name[4]);
}
else{
if((number%1000/100) != 0)
strcat(str,digits[0]);
}
if((tmp = number % 1000%1000%10) != 0)
strcat(str,digits[tmp]);
}
}
}