C++ 我的for循环出现问题
所以我正在为Uni制作一个因子循环程序,我很少使用循环 这个想法是你输入一个正数,它会帮你计算, e、 g.如果选择数字5,则将执行以下操作: 1*2*3*4*5=120,它对我的大多数输入都有效,但当我通过1时,它没有得到正确的结果 只是想知道是否有人知道我的foor循环出了什么问题C++ 我的for循环出现问题,c++,loops,C++,Loops,所以我正在为Uni制作一个因子循环程序,我很少使用循环 这个想法是你输入一个正数,它会帮你计算, e、 g.如果选择数字5,则将执行以下操作: 1*2*3*4*5=120,它对我的大多数输入都有效,但当我通过1时,它没有得到正确的结果 只是想知道是否有人知道我的foor循环出了什么问题 #include <iostream> using namespace std; int main() { int i, n, factorial = 1; cout<&
#include <iostream>
using namespace std;
int main() {
int i, n, factorial = 1;
cout<<"Enter a positive integer: ";
cin>>n;
if (n<=0) {
cout << "Please enter a non-negative number!!!\n";
}
else {
for (i = 1; i <=n; ++i) {
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
}
我把它打印出来的方式是:
Enter a non-negative integer:
9! = 362880
当我输入一个大于12的数字时,例如13,我得到
Enter a non-negative integer:
13! = 1932053504
答案是错误的,我也需要它是:
Enter a non-negative integer:
13! = 6.22702e+09
干杯。查看此链接以查看每个数据类型范围(int类型的最小值和最大值): 有关科学符号,请检查以下内容: 还可以查看此链接以了解溢出的概念:
您可以使用long int,最多可以得到20个正确值!大约如此。这是因为13的输出值超过了有符号整数的最大值(4字节),并导致整数溢出 考虑将
int
更改为long-long-int
(8字节)
#包括
使用名称空间std;
int main(){
长整型i,n,阶乘=1;
coutn;
如果(n使用
#包括
使用名称空间std;
//输入验证
int getNumber(){
int n;
做{
cout>n;
}而(cin&n<0);
返回n;
}
int main(){
int n=getNumber();
无符号长阶乘=1;//可能的最大值
对于(int i=1;i但当我通过1时,它没有得到正确的结果
给出一些示例输入、预期输出和实际输出。您的代码对输入1很好,阶乘结果为1。您要寻找的输出是什么。要使这成为一个正确的阶乘计算器,请记住0!=1
我刚刚发现我需要使用长int对于变量,但仍然停留在科学记数法位。这到底是如何进行升级的???第一次升级甚至在添加样本输入和输出之前就已经进行了。非常感谢,只有一个问题,你知道我如何用科学记数法计算出结果,只是输出,而不是“13!”只是“6227020800”我希望将其表示为“13!=6.22702e+09”。我希望这仅适用于大于或等于10的值,我会使用if语句吗
Enter a non-negative integer:
13! = 6.22702e+09
#include <iostream>
using namespace std;
int main() {
long long int i, n, factorial = 1;
cout<<"Enter a positive integer: ";
cin>>n;
if (n<=0) {
cout << "Please enter a non-negative number!!!\n";
}
else {
for (i = 1; i <=n; ++i) {
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
}
#include <iostream>
using namespace std;
// Input validation
int getNumber() {
int n;
do {
cout << "Enter a non-negative number!\n";
cin >> n;
} while (cin && n < 0);
return n;
}
int main() {
int n = getNumber();
unsigned long long factorial = 1; // Maximum possible
for (int i = 1; i <= n; ++i)
factorial *= i;
cout<< n << "! = " << factorial;
return 0;
}