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
相关产品推荐
相关产品推荐

