题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
#include <iostream> using namespace std; #include<string> string zh[10] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; string unit[17] = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟", "万"}; void before_point(string s) { if(s=="0") { return; } int len = s.size() - 1; if (!(len % 4 == 1 && s[0] == '1')) { //防止出现壹拾伍这样的数, cout << zh[s[0] - '0']; } cout << unit[len]; for (int i = 1; i <= len; i++) { if ((len - i) % 4 == 0 && s[i] == '0') { //万,亿这些位置为0时,需要加上单位万或者亿等 cout << unit[len - i]; continue; } if (s[i] != '0') { //如果是字符串中的数字,一定要加上''!!!! if (s[i - 1] == '0'&&((len-i)!=3)) {//十万以上的数字接千不用加“零”,例如,30105000.00应写作“人民币叁仟零拾万伍仟元整” cout << "零"; } if (!((len-i) % 4 == 1 && s[i] == '1')) { //防止出现壹拾伍这样的数, cout << zh[s[i] - '0']; } cout << unit[len - i]; } } cout << "元"; } void after_point(string s) { if (s == "00") { cout << "整"; return; } if (s[0] != '0') { cout << zh[s[0] - '0']; //5.03 输出5元三分 cout << "角"; } if (s[1] == '0') { return; } else { cout << zh[s[1] - '0']; cout << "分"; } } int main() { string s; while (getline(cin, s)) { string s1 = s.substr(0, s.find('.')); string s2 = s.substr(s.find('.') + 1); cout << "人民币"; before_point(s1); after_point(s2); cout << endl; } return 0; }