数字0到9999转换大写汉字整数程序(C语言实现)

输入:9001

输出:九千零一




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

#define DEBUG printf
/*========================================================*/

int len_num(int num);   //to judge the length of the number
char* my_itoa(int num, int len); //to transform the number to a string
char* handle_str(char* str_num, int len); //transform num to NUM

/*========================================================*/

int main()
{
	float num_test;
	int num, len;
	char* str_num;
	char* str_result;
	
	while(1)
	{		
		printf("Please input a number:  ");
		
		if(!(scanf("%f", &num_test)))
		{
			printf("Invalid:data type not correct.\n");
			break;
		}	
		else
		{
			num = (int)num_test;
   		
			if (num_test != num)
			{
				printf("Invalid:number type not correct.\n");
				printf("number: %f\n", num_test);
			}
			else if (num == 0)
			{
				printf("Number: 0\nLength: 1\nResult: 零\n");
			}
			else if (num_test > 9999 || num_test < 0)
			{
				printf("Invalid:number overflow.\n");
				printf("number: %d\n", num);
			}
			else
			{
				len = len_num(num);
		
				str_num = my_itoa(num, len);

				str_result = handle_str(str_num, len);
	
				printf("Number: %d\nLength: %d\n", num, len);
				printf("Result: %s\n", str_result);
	
			}
		}
	}
	return 0;
}

/*========================================================*/

/*
  function:  to get the length of the number
  input : the input number, int num
  output: the length of the number, int num_len
*/

int len_num(int num)
{
	int num_len;

	if(num <= 9999 && num >= 1000)
		num_len = 4;
	else if(num <= 999 && num >= 100)
		num_len = 3;
	else if(num <= 99 && num >= 10)
		num_len = 2;
	else if(num <=9 && num >=0)
		num_len = 1;
	return num_len;
}

/*
  function:  to transform number to a string
  input : int num, int len
  output: char* point to a string
*/

char *my_itoa(int num, int len)
{
	char *temp;
	int i;
	temp =(char*)malloc(sizeof(char)*len);

	for (i = 1; i <= 5; i++)
	{
		if(len-i != -1)
		{
			temp[len-i] = num % 10 + '0';
			//		DEBUG("temp%d %c",i,temp[len-i]);
			num  = num / 10;
		}
		else
			return temp;
	
	}
}


/*
  function:  to transform num to NUM
  input : char* str_num 
  output: None
*/

char* handle_str(char* str_num, int len)
{
	int i=0, k;
	char *str_result;
	
    static char num_trans[10][4] = {"零","一","二","三","四","五","六","七","八","九"};
	static char num_value[4][4] = {"千","百","十",'\0'};
	
	str_result = (char*)malloc(sizeof(char)*32);
	
	for(k = 4-len; k <=3 ; k++)
	{
		int j;
		j = str_num[i]-'0';
		if(!(str_num[i] == '0' && (str_num[i+1] == '0' || i ==len-1)))
			strcat(str_result, num_trans[j]);
					
		if(j != 0)
		{
			strcat(str_result, num_value[k]);
		}
		i++;
	}
	return str_result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值