第一次尝试在线编程给出错误的答案



这是一个阶乘程序,我在编码网站上制作。请帮我找出为什么是错的?

#include <iostream>
using namespace std;
int main()
{
    int i, j, f = 1;
    int t, a[100];
    cin >> t;//enter test cases
    for (i = 0; i < t; i++)
        cin >> a[i];//enter all the cases one by one
    for (i = 0; i < t; i++)
    {
        for (j = 1; j <= a[i]; j++)
            f = f*j;
        cout << f;//displays each factorial
    }
    return 0;
}

您应该在每个测试用例开始时将 f 的值重新初始化为 1。

#include <iostream>
using namespace std;
int main()
{
    int i, j, f = 1;
    int t, a[100];
    cin >> t;//enter test cases
    for (i = 0; i < t; i++)
        cin >> a[i];//enter all the cases one by one
    for (i = 0; i < t; i++)
    {
        f = 1 // add this line
        for (j = 1; j <= a[i]; j++)
            f = f*j;
        cout << f;//displays each factorial
    }
    return 0;
}

每次计算阶乘时,都应该重新初始化factorial variable f的值,也不需要使用数组来存储所有不必要地浪费内存的阶乘情况。

以下是优化的解决方案:

#include <iostream>
using namespace std;
int main()
{
    int i, j, f,num;
    int t;
    cin >> t; //enter test cases
    for (i = 0; i < t; i++)
    {
        cin >> num;
        f = 1;
        for (j = 1; j <= num; j++) {
            f = f * j;
        }
        //displays each factorial
        cout << f << endl;
    }
    return 0;
}

相关内容

最新更新