如何修复此循环

时间:2019-10-24 09:56:44

标签: c++ algorithm factorial

我无法初始化i并更改x的值 我试图找到阶乘形式的逆序

#include <iostream>
using namespace std;

void main()
{
    int x, i;
    cin >> x;
    float fact = x*i;
    do { 
        fact = fact*i;
        i = x -1;
        --x;
    } while( x >= 0 );
    cout << fact << endl; 
}

我希望输出5! = 120

4 个答案:

答案 0 :(得分:2)

删除变量i,因为我们不需要它。由于我们不希望while

,因此也请更正fact*0循环中的条件
int main() {

    int x;
    std::cin >> x;
    float fact = 1;
    do {
        fact = fact * x;
        x--;
    } while (x > 0);
    std::cout << fact << std::endl;
}

答案 1 :(得分:2)

您没有初始化i,并且您的算法略有缺陷。在代码中注释:

#include <iostream>

int main() // void isn't valid
{
    int i = 1; // initialize
    int x;
    std::cin >> x;
    float fact = (x * i);
    do {
        fact = fact * i;
        i = x - 1;
        --x;
    } while(x > 0); // if x==0 is accepted it means i==0 next round and "fact = fact * 0"
    std::cout << fact << "\n";
}

您可以改为编写如下函数:

#include <limits> // std::numeric_limits

float fact(int x) {
    float fact = 1.f;

    if(x < 0) { // let's not deal with negative factorials
        fact = std::numeric_limits<float>::quiet_NaN();
    } else {
        for(; x > 0; --x) {
            fact *= static_cast<float>(x);
        }
    }

    return fact;
}

并检查它是否正常:

int main() {
    for(int i = -1; i < 10; ++i) {
        std::cout << i << "\t" << fact(i) << "\n";
    }
}

输出:

-1      nan
0       1
1       1
2       2
3       6
4       24
5       120
6       720
7       5040
8       40320
9       362880

答案 2 :(得分:1)

#include<iostream>
using namespace std;


int main()
{
    int x,i=1;
    cin>>x;
    float fact = x*i;
    do{ 
        fact=fact*i;
        i=x-1;
        --x;
    }while (x>0);
    if (x == 0)
       fact = 1;
    cout<<fact<<endl; 
}

您的代码有一些细微的变化。这可能会有所帮助:)

答案 3 :(得分:0)

稍作修改的版本:(不检查是否超限)

#include <iostream>
using namespace std;

int factorial (int x){  // a recursive function

    int res = 0;

    if (x ==1) return 1;
    else
        return x * factorial (x -1);   // call the function, with the immediate previous number
}

int main(void)
{
    int x = 0;
    int fact = -1;
    cin>>x;

    fact = factorial(x);
    cout<<fact<<endl; 
}

您在这里不需要额外的变量。