题解 | #人民币转换#

人民币转换

https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b

double类型可能会丢失精度,第一次知道。。。😂
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

string kkbd(double n) {//让金额数字快快变大变成中文大写数字
    string s;
    n += 0.005;
    int x = n, i = 0, tag = 0, tag1 = 0, i1 = 0;//x用于取整,i记录金额的位数,i1用来记录万和亿的进位,tag用来记录是否为零,初始化为零则可避免在10,100等后输出0;
    vector<string>daxie = { "零","壹","贰","叁","肆","伍","陆","柒","捌","玖" };
    vector<string>weishu = { "","拾","佰","仟" };
    vector<string>weishu2 = { "元","万","亿" };
    if (x == n) s = "整";//无小数说明是整钱;
    else {
        int a = (n - x) * 100;
        if (a % 10 != 0) s = daxie[a%10] + "分";
        if (a / 10 != 0) s = daxie[a / 10] + "角" + s;
    }
    while (x) {
        if (tag1 == 0) {
            s = weishu2[i1] + s;
            tag1 = 1;
        }
        if (x % 10 == 0 && tag != 0) {
            s = daxie[x % 10] + s;
            tag = 0;
        }
        if (x % 10 > 0) {
            if (i == 1 && x % 10 == 1) s = weishu[i] + s;
            else
                s = daxie[x % 10] + weishu[i] + s;
            tag = 1;
        }
        i == 3 ? (i = 0, ++i1, tag1 = 0, tag = 0) : ++i;
        x /= 10;
    }
    s = "人民币" + s;
    return s;
}

int main() {
    double n;
    cin >> n;
    string s = kkbd(n);
    cout << s;
}



全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务