數字轉中文表示

此處表達式不超過萬。

注意的地方:1000,可以1001,即0的情況 (首,中,尾),11 ,12等,10 20 等情況!

此處未考慮負數情況,可以加以判斷,並且在開始加入負

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string int_to_num(int num);

int main()
{
	int num;
	cin>>num;
	
	cout<<int_to_num(num)<<endl;
	return 0;
}




string int_to_num(int num)
{
	string num_str[] = {"零","一","二","三","四","五","六","七","八","九"};
	string base_str[] = {"","十","百","千","萬" };
	
	string res;
	int count = 0;

	if(num == 0) return num_str[0];
	int num_low[10];

	while(num != 0)
	{
		
		int num_digit = num%10;
		num = num/10;

		num_low[count] = num_digit;

		if(num_digit  == 0 && count == 4 )//字母頭爲0
		{
			if(num_low[count-1] == 0)//高位連續爲0知道萬位!!
			{
				res = res.substr(num_str[0].size(),res.size()-num_str[0].size());
			}
			
			break;
		}
		if(num_digit  == 0&&count >= 1 && num_low[count-1] != 0 )//防止1000,可以1001,即0的情況
		{
			res = num_str[num_digit]+res;
		}
		else if(num_digit  == 1&&count == 1&&num == 0)//防止11,12等情況
		{
			res = base_str[num_digit]+res;
		}
		else
		{
			if(num_digit > 0)//必須大於0
			{
				res = num_str[num_digit]+base_str[count]+res;
			}
			
		}
		count++;
		if(count >= 5)break;
	}

	return res;

}
如果代碼有bug,希望各位指正,謝謝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章