【团体程序设计天梯赛-练习集】L1-017--到底有多二

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34072526/article/details/88766447

一个整数“犯二的程度”定义为该数字中包含2的个数与其位数的比值。如果这个数是负数,则程度增加0.5倍;如果还是个偶数,则再增加1倍。例如数字-13142223336是个11位数,其中有3个2,并且是负数,也是偶数,则它的犯二程度计算为:3/11×1.5×2×100%,约为81.82%。本题就请你计算一个给定整数到底有多二。

输入格式:

输入第一行给出一个不超过50位的整数N。

输出格式:

在一行中输出N犯二的程度,保留小数点后两位。

输入样例:

-13142223336

输出样例:

81.82%


代码

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
    string a;
    string::iterator it;
    int len, cnt = 0;
    float bei = 1.0, res = 0.0;
    cin >> a;
    it = a.end() - 1;
    if((*it - 48) % 2 == 0){
        bei *= 2.0;
    }
    it = a.begin();
    if(*it == '-'){
        bei *= 1.5;
        len = a.length() - 1;
        it = a.begin() + 1;
    }
    else{
        len = a.length();
    }
    for(; it != a.end(); it++){
        if(*it == '2'){
            cnt++;
        }
    }
    res = (float)cnt / len * bei * 100;
    cout << setiosflags(ios::fixed) << setprecision(2) << res << "%" << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34072526/article/details/88766447