c++ - 有什么办法可以去掉 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;
}
}
解决方案
是的,添加一个 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;
}
}
推荐阅读
- flutter - Dio 4.0.0 (Dart) 中奇怪的 BaseOptions 问题
- python - 获取属于特定类的数据子集
- java - 从动态字符串中获取运算符之前的子字符串
- python - 为什么 discord 不返回 COVID19 结果数据?
- amazon-web-services - 创建 AWS 弹性 Beanstalk Spring 实例并将其分配给 VPC
- hibernate - reddison hibernate 作为二级缓存的问题
- java - 短期 Java CLI 应用程序的性能
- html - 如何让一件物品在另一件物品开始收缩之前完全收缩?
- php - 获取每个帖子的标签(wordpress php)
- sql - 删除 Laravel 8 中未使用的组