简体   繁体   English

在 c++ 中打印一个数的阶乘的程序

[英]Program to print Factorial of a number in c++

Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N. For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120 Q) 编写一个程序,定义并测试一个阶乘 function。一个数的阶乘是从 1 到 N 的所有整数的乘积。例如,5 的阶乘为 1 * 2 * 3 * 4 * 5 = 120

Problem: I am able to print the result,but not able to print like this:问题:我能够打印结果,但不能像这样打印:

let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;

My Code:我的代码:

# include <bits/stdc++.h>

using namespace std;


int Factorial (int N)
{
    int i = 0;int fact = 1;

    while (i < N && N > 0) // Time Complexity O(N)
    {
        fact *=  ++i;
    }

    return fact;
}

int main()
  {
    int n;cin >> n;
    
    cout << Factorial(n) << endl;
    return 0;
  }

I am able to print the result,but not able to print like this: let n = 5 Output: 1 * 2 * 3 * 4 * 5 = 120;我能够打印结果,但不能像这样打印:let n = 5 Output: 1 * 2 * 3 * 4 * 5 = 120;

That's indeed what your code is doing.这确实是您的代码正在做的事情。 You only print the result.您只打印结果。 If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.如果您想在打印结果之前打印从 1 到 N 的每个 integer,则需要更多 cout 调用或其他方式来操作 output。

This should only be an idea this is far away from being a good example but it should do the job.这应该只是一个想法,这远不是一个很好的例子,但它应该可以完成工作。

int main()
  {
    int n;cin >> n;
    
    std::cout << "Factorial of " << n << "!\n";
    for (int i =1; i<=n; i++)
    {
        if(i != n)
            std::cout << i << " * ";
        else
            std::cout << n << " = ";
    }

    cout << Factorial(n) << endl;
    return 0;
  }

Better approach using std::string and std::stringstream使用std::stringstd::stringstream的更好方法

#include <string>
#include <sstream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    stringstream sStr;
    sStr << "Factorial of " << n << " = ";
    
    for (int i = 1; i <= n; i++)
    {
        if (i != n)
            sStr << i << " * ";
        else
            sStr << i << " = ";
    }
    sStr << Factorial(n) << endl;
    cout << sStr.str();
    return 0;
}

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

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