【PAT 甲級】1082 Read Number in Chinese (25 分)

1082 Read Number in Chinese (25 分)

Given an integer with no more than 9 digits, you are supposed to read it in the traditional Chinese way. Output Fu first if it is negative. For example, -123456789 is read as Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu. Note: zero (ling) must be handled correctly according to the Chinese tradition. For example, 100800 is yi Shi Wan ling ba Bai.

Input Specification:

Each input file contains one test case, which gives an integer with no more than 9 digits.

Output Specification:

For each test case, print in a line the Chinese way of reading the number. The characters are separated by a space and there must be no extra space at the end of the line.

Sample Input 1:

-123456789

Sample Output 1:

Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu

Sample Input 2:

100800

Sample Output 2:

yi Shi Wan ling ba Bai

我的思路

調試了半天,處理各種細節問題,詳情看代碼中的註釋吧。注意:

1. PAT 已經不支持 gets(),會報錯 error: 'gets' was not declared in this scope,需用cin.getline(s,長度)代替;

2. 注意100001234這種數的輸出是一億一千二百三十四

 

我的代碼 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std; 
int main()
{
	//初始化 
	int f=0, length, t;
	char s[11]={'*','*','*','*','*','*','*','*','*','*'};  //避免初始化0,影響判斷 
	//用於位數的漢字表示,把空格和個位表示也存入數組,便於輸出格式 
	char w[][11] = {" Yi"," Qian"," Bai"," Shi"," Wan"," Qian"," Bai"," Shi",""};
	//用於數字的漢字表示,存成數組就不用switch選了 
	char n[][11] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
	
	//PAT已經不支持gets(),會報錯error: 'gets' was not declared in this scope 
	//gets(s);

	cin.getline(s,11);
	length = strlen(s);
	//判斷正負 
	if (s[0]=='-')
	{
		printf("Fu ");
		f=1;  //數據處理時,數據從下標1開始 
	}
	t = length-f;  //求除了負號以外的位數 
	
	for (int i=f; i<length; i++)
	{
		//處理0的輸出 
		if (s[i]=='0')
		{ 
			if ((s[i+1]!='0' && i!=length-1 && i!=length-5) || (t==1))
			{
				if (i!=f) printf(" ");  //如果不是第一個數,則開頭輸出一個空格 
				printf("%s", n[0]);
			}
			if (i==length-5) 
			{  //如果是萬位上的0 
				if (s[i-1]=='0'&&s[i-2]=='0'&&s[i-3]=='0'&&s[i+1]!='0')
				{  //若存在億位,且萬位到億位之間全爲0,若千位非0,則需輸出一個"ling" 
					printf(" %s", n[0]); 
				} else if (!(s[i-1]=='0'&&s[i-2]=='0'&&s[i-3]=='0')) {
					printf("%s", w[4]);  //若萬位到億位之間存在非0數,則輸出"wan" 
				}				
			}
		} else {  //非0數的輸出 
			int temp = (int)s[i] - (int)'0';  //字符轉整數 
			if (i!=f) printf(" ");  
			printf("%s%s", n[temp], w[9-length+i]);
		}
	}
	
	return 0;
 } 

 

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