为什么这样写就全WA了?

P1009 [NOIP1998 普及组] 阶乘之和

_DCH__1236 @ 2023-01-18 12:15:23

#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1005;

int f[N],b[N];
int n;

int main()
{
    f[0] = 1, b[0] = 1;
    cin >> n;

    for (int i = 2; i <= n; i++)
    {
        for (int j = 0; j < N; j++)
        {
            f[j] *= i;//计算阶乘
        }

        for (int j = 0; j < N; j++)
        {
            if (f[j] > 9)
            {
                f[j + 1] += f[j] / 10;
                f[j] %= 10;
            }
        }

        for (int j = 0; j < N; j++)
        {
            b[j] += f[j];//计算阶乘和
            if (b[j] > 9)
            {
                b[j + 1] += b[j] / 10;
                b[j] %= 10;
            }
        }
    }
    int t = N;
    while (!b[t] && t >= 0)t--;

    for (int i = t; i >= 0; i--)cout << b[i];
    cout << endl;

    return 0;
}

by mysterys @ 2023-01-18 12:33:25

@_DCH__1236

  1. 请看看输出
  2. 下次求助前先看看自己样例过了没

by mysterys @ 2023-01-18 12:37:27

@_DCH__1236 另外,如果全WA试着看看算法标签,里面有写要用高精度。而您的代码没有用到高精度


by NFGase @ 2023-01-18 12:48:01

注意审题

“用高精度计算”


by _DCH__1236 @ 2023-01-18 14:34:39

@mysterys 样例过了,我这用的就是高精啊


by _DCH__1236 @ 2023-01-18 14:37:23

@xDNA 我是看的题解,原题解是每个循环的次数都是100。


by NFGase @ 2023-01-18 14:53:32

@_DCH__1236 整形数组输入是不同元素要有空格才能读入,所以当然错了啊,只能用string 或char数组,不信你试试


by NFGase @ 2023-01-18 14:57:30

@_DCH__1236 阶乘高精模板: (不是这题答案)

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

int main(){
    int a[99999] = {1}, lena = 1, lenans = 0, in = 0;
    long long n;
    cin >> n;
    for(int i = 1; i <= n; i++){
        lenans = lena;
        for(int j = 0; j < lenans; j++){
            a[j] = (a[j] * i) + in;
            in = a[j] / 10;
            a[j] %= 10;
        }
        while(in != 0){
            int b = in % 10;
            a[lenans] = b;
            in /= 10;
            lenans++;
        }
        lena = lenans;
        in = 0;
    }
    for(int i = 0; i < lena; i++)
        cout << a[lena - i - 1];
    return 0;
}

|