You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++编写整数阶乘程序如何去除输出末尾多余的*号

问题原因
  • 第一,你代码中的count变量没有初始化,运行时会出现未定义行为,大概率无法正常按预期进入循环。
  • 第二,循环内每次输出数值后都会固定拼接*,所以最后一个数值末尾也会多出来多余的星号。
修改方案

我们调整输出逻辑即可:仅当当前输出的不是最后一个数的时候,才在数值后加*,最后一个数后不加符号,同时修正count初始化的问题,补充对0阶乘的兼容处理。

修改后完整代码
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
            
    int n, count = 0, 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;
            // 只有不是最后一个数的时候才输出*
            if(count < n){
                cout << " * ";
            }
        }
        cout << " = " << factorial;
    }
    return 0;
}
验证效果

输入5的时候,输出就会变成你需要的格式:

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

内容的提问来源于stack exchange,提问作者Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:48:02