L1-017 到底有多二 C++(个人练习)

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

输入格式:

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

输出格式:

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

输入样例:

-13142223336

输出样例:

81.82%

鸣谢安阳师范学院段晓云老师和软件工程五班李富龙同学补充测试数据!

代码长度限制16 KB

时间限制400 ms

内存限制64 MB

下面是我的代码展示(有点low)

#include<iostream>
#include<string>
#include <iomanip>

using namespace std;
int main()
{
    string a;
    getline(cin, a);
    int l = a.size();
    int x = 0, pre=0, y = 0;
    double  result;
    if (a[0] == '-')
        y = 1;
    if ((a[l - 1] - 48) % 2 == 0)
        pre = 1;
    for (int i = 0; i<(y?l-1:l); i++)
    {
        if (a[i] == '2')
            x += 1;
    }
    if (y) 
        l -= 1;
    if (pre && y)
        result = (double)x / l * 1.5 * 2 * 100;
    else if (pre && !y)
        result = (double)x / l * 2 * 100;
    else if (!pre && y)
        result = (double)x / l * 1.5 * 100;
    else
        result = (double)x / l * 100;
    cout << setprecision(4) << result<< "%" << endl;
}

但具有精度缺失的问题,找不到原因,希望大佬指点

猜你喜欢

转载自blog.csdn.net/m0_63953970/article/details/129368013