コードの一般的な説明が必要です:
ケース1)
この階乗関数では、num
が0の場合、0 !、つまり1を返しますか?
ケース2)数値が1より大きい場合return fact
、それは階乗値ですか?
私はそれを理解してreturn 1
おり、return 0
両方とも結果の生成を成功させるためのものです。
では、なぜこの場合は0を返すことができないのですか?
double factorial(int num)
{
int fact = 1;
int i = 1;
if (num == 0)
return 1;
else
while (num >= i)
{
fact = fact*i;
i++;
}
return fact;
#include <iostream>
using namespace std;
int factorial(int num) //I changed this to return int since you are taking int and int*int will always be int
{
int fact = 1;
//int i = 1; //dont need this
if (num == 0)
return fact; //You can just say return `fact` or `return 1` - i like to make my code readable - s I used `return fact`
//I also prefer to set the value of fact as 1 here and return the 1 at bottom so we only have one return statement
//but thats just me - having 2 return statements should be fine if used wisely
/*while (num >= i) //thispart was wrong i reedited it into a better and more efficient code below
{
fact = fact*i;
i++;
}*/
else
{
while(num>1) // so lets say we enter 4 - 4 is larger than 1
{
fact*=num; //first step through it will be fact = fact * num; fact is 1 at first loop so it will be 1 * 4 and we put that value into fact
num--; //here we set num to 3 for next loop and we repeat :D
}
}
return fact; //here we return the value
}
int main() //just a normal main
{
int number;
cout<<"Enter number: \n";
cin>>number;
cout<<"Factorial of "<<number<<" is "<<factorial(number);
return 0;
}
あなたの質問は完全に良かったと思います。私自身初心者プログラマーであるため、このような質問を見るときにも役立ちます。お役に立てれば!がんばろう!
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加