简体   繁体   English

C ++阶乘程序做奇怪的数学

[英]C++ factorial program doing strange math

Very new to c++. C ++的新手。 Making this factorial program, and somehow I've scraped through the code and built something, but the value it returns is always 10 times the correct value. 编写这个析因程序,并以某种方式我遍历了代码并构建了一些东西,但是它返回的值始终是正确值的10倍。 For example, factorial for 5 is computed at 1200 instead of 120, and factorial of 3 is computed at 60. Why the extra unit? 例如,5的阶乘是在1200而不是120处计算的,3的阶乘在60的情况下计算。为什么要使用额外的单位?

This is the code: 这是代码:

#include <iostream>

using namespace std;

int main() {

    int i, j, num;

    cout << "Compute factorial: " << endl;

    cin >> num;

    for (i=1; i<num; i++){

        for (j=num; j>1; j--)

            num *=(j-i);

        cout << num;
    }

    return 0;
}

All you need is one loop. 您只需要一个循环。 This way should be much simpler. 这种方法应该简单得多。

#include <iostream>

using namespace std;

int main() {

    int i, j=1, num;

    cout << "Compute factorial: " << endl;

    cin >> num;

    for (i=num; i>0; i--){
        j *= i;
    }

    cout << j << endl;
}
for (i=1; i<num; i++){

     num *=i;
}

This should be enough 这样就足够了

I think you are not quite clear about for loop,and be careful with the change of num try this piece of code, hope it will help 我认为您不太了解for循环,请注意num的更改,请尝试这段代码,希望对您有所帮助

#include <iostream>

using namespace std;

int main() {

int i, j, num;

cout << "Compute factorial: " << endl;

cin >> num;
int output_num = 1;
for (i=1; i<=num; i++){

        output_num *= i;

}
cout << output_num;

return 0;
}

Use this code : 使用此代码:

#include<iostream>
using namespace std;
int main()
{
int num,fact=1;
cout<<" Enter the no. to find its factorial:";
cin>>num;
for(int a=1;a<=num;a++)
{
fact=fact*a;
}
cout<<"Factorial of a given Number is ="<<fact<<endl;
return 0;
}

Output : 输出:

在此处输入图片说明

using two loops for computing factorial is very complex..... and you do not need it. 使用两个循环来计算阶乘非常复杂.....而您并不需要它。 Try this 尝试这个

#include <iostream>

using namespace std;

int main() {

    int i,num;
    cout << "Compute factorial: " << endl;
    cin >> num;
    for(i=num;i>1;--i)
        num*=(i-1);

        cout << num;

    return 0;
}

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

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