繁体   English   中英

C ++程序的意外输出

[英]Unexpected output of c++ program

我正在解决http://codeforces.com/problemset/problem/552/B

在我的第一次尝试中,我想到了类似的东西:

#include <bits/stdc++.h>
using namespace std;
int digit(long a){
    int i=0;
    while(a){
        a/=10;
        i++;
    }
    return i;
}
int main()
{
    long n;
    long long s=0;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    int dig=digit(n),i=0;
    while(i<dig){
        s+=(n-pow(10,i)+1);
        i++;
    }
    cout<<s;
    return 0;
}

但是为了输入

1000000

我的程序输出

5888895

我期待

5888896

在第二次尝试中,我为自己编写了pow函数:

#include <bits/stdc++.h>
using namespace std;
int digit(long a){
    int i=0;
    while(a){
        a/=10;
        i++;
    }
    return i;
}
long long pow1(int a){
    long long s=1;
    while(a--){
        s*=10;
    }
    return s;
}
int main()
{
    long n;
    long long s=0;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    int dig=digit(n),i=0;
    while(i<dig){
        long long aux=pow1(i);
        s+=(n-aux+1);
        i++;
    }
    cout<<s;


    return 0;
}

这次是正确的,如何解释其背后的工作?

内置pow功能的问题在于,其功能不如您的功能那么精确。 pow计算x到y的值为exp(y*log(x)) 该通用公式适用于所有(甚至是非整数)指数,并且其性能(主要)与参数无关。 该公式的问题在于, pow(10,2)可能是99.9 ,当将其转换为整数类型时会被截断为99。 尝试pow(10,i) + 0.5进行适当的舍入。

您可能不需要这里的pow 这可以按预期工作,并且速度更快。

#include <iostream>
typedef unsigned long long ull;
using namespace std;

ull count(ull n) {
    ull i = 0;
    for (; n; ++i) n /= 10;
    return i;
}

int main() {
    ull n;
    cin >> n;
    ull digits = count(n);
    ull ans = digits * (n + 1);
    for (ull i = 0, j = 1; i < digits; ++i, j *= 10)
        ans -= j;
    cout << ans;
    return 0;
}

传递所有测试用例codeforces.com

您只需要将pow(10,i-1)乘以0.1。 那将完成您需要的工作。

#include <iostream>
#include <cmath>
using namespace std;
int digit_calc(long long num);
long long digit_counter(long long num, int digit);
int main()
{
    long long num,digit,total;
    cin>>num;
    digit=digit_calc(num);
    total=digit_counter(num, digit);
    cout<<total<<endl;
    return 0;
}
int digit_calc(long long num){
    int digit=0;
    while(num){
        digit++;
        num=num/10;
    }
    return digit;
}
long long digit_counter(long long num, int digit){
    long long sup,net,total=0;
    while(num){
        sup=0.1*(pow(10,digit)-1);
        net=num-sup;
        total=total+(net*digit);
        num=sup;
        digit--;
    }
    return total;
}

它通过了Codeforce上的所有测试用例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM