首页 > 解决方案 > 有什么办法可以去掉 C++ 程序中整数阶乘的最后一位数字中的“*”

问题描述

我的代码的输出是:

5! = 1 * 2 * 3 * 4 * 5 * = 120

如何删除最后一个*以获得此输出:

5! = 1 * 2 * 3 * 4 * 5 = 120 
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
            
    int n, count, factorial = 1;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << n << "! = ";
    
    if (n < 0){
        cout << "Error! Factorial of a negative number doesn't exist.";
        }
    else{
        while(count < n){
        count++;
        factorial = factorial * count ;
        cout << count << " * ";  
        }
            cout << " = " << factorial;
    }
}

标签: c++

解决方案


是的,添加一个 if 来检查您是否不在最后一个号码上。(也不要使用 using namespace std,为什么“using namespace std;”被认为是不好的做法?

#include <iostream>

int main(int argc, char** argv)
{

    int n = 0;
    int count = 0;
    int  factorial = 1;

    std::cout << "Enter a positive integer: ";
    std::cin >> n;
    std::cout << n << "! = ";

    if (n < 0)
    {
        std::cout << "Error! Factorial of a negative number doesn't exist.";
    }
    else
    {
        while (count < n)
        {
            count++;
            factorial = factorial * count;
            std::cout << count;

            // only show * if not on last number
            if (n != count) std::cout << " * ";
        }
        std::cout << " = " << factorial;
    }
}

推荐阅读