题解 | #人民币转换#

人民币转换

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

#include <iostream>//和42学英语很像
#include <vector>
using namespace std;
vector<string> str{"壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
vector<string> str1{"拾", "贰拾", "叁拾", "肆拾", "伍拾", "陆拾", "柒拾", "捌拾", "玖拾"};
string myfunc1(string& s) {
    string sout;
    if(s[0]!='0'){
        sout += str[s[0] - '0' - 1];sout += "仟";
    }

    if (s[1] != '0') {
        sout += str[s[1] - '0' - 1];
        sout += "佰";
    }
    if (s[2] == '0') {
        if (s[3] != '0') {
            if(s[0]!='0' || s[1] != '0') sout += "零";
            sout += str[s[3] - '0' - 1];
        }
    } else {
        if(s[0]!='0' && s[1] == '0') sout += "零";
        sout += str1[s[2] - '0' - 1];
        if (s[3] != '0') {
            sout += str[s[3] - '0' - 1];
        }
    }
    return sout;
}
int main() {
    double a;
    cin >> a;
    // string s1;cin>>s1;
    // double a=stod(s1);
    int b = a * 1000;
    int bf = b % 100;bf/=10;
    b /= 100; //bf 百分位
    int sf = b % 10;
    b /= 10; //sf 十分位  现在b就是整数部分
    string s;
    s += "人民币";
    //整数部分
    string zs = to_string(b);
    int n = zs.size();
    if (n > 8) { //有亿位
        for(int i=0;i<(12-n);i++) {zs="0"+zs;}
        string s1=zs.substr(0,4),s2=zs.substr(4,4),s3=zs.substr(8,4);
        s+=myfunc1(s1);s+="亿";
        s+=myfunc1(s2);s+="万";
        s+=myfunc1(s3);s+="元";
    } else if (n <= 8 && n > 4) { //千万~万
        for(int i=0;i<(8-n);i++) {zs="0"+zs;}
        string s1=zs.substr(0,4),s2=zs.substr(4,4);
        s+=myfunc1(s1);s+="万";
        s+=myfunc1(s2);s+="元";
    }
    else{
        for(int i=0;i<(4-n);i++) {zs="0"+zs;}
        s+=myfunc1(zs);
        if((zs[0]-'0')||(zs[1]-'0')||(zs[2]-'0')||(zs[3]-'0'))s+="元";
    }
    // s += "元";
    //小数部分
    if (bf == 0 && sf == 0) s += "整";
    if (sf != 0) {
        s += str[sf - 1];
        s += "角";
        if (bf != 0) {
            s += str[bf - 1];
            s += "分";
        }
    }
    if (sf == 0 && bf != 0) {s += str[bf - 1];s += "分";}
    cout << s;
}

全部评论

相关推荐

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