루프 곱하기 int를 낮추십시오
-
26-12-2019 - |
문제
다음 루프가 있습니다.
public int multiply(int Z)
{
//Z=5
for (int i = 1; i <= Z; i++)
{
int Y=Z*i;
return Y;
//i wanna Y multiply x*4*3*2*1 all loops in one result
}
return Z;
}
.
어떻게 해야할지 알고 싶습니다 :
새로운 곱하기 int y= z * 4 * 3 * 2 * 1 만들기 곱하기 결과는 콘솔 쓰기 라인에 있습니다 :
("value for your loop is " +test.multiply(5));
value for your loop is 120
.
이것은 for
루프에 의해 수행 될 수 있거나 잘못 되었습니까?
해결책
당신이 실제로 당신이 Z의 계승을 계산하고 싶다는 것을 의미합니다.
public int Factorial(int Z)
{
if (Z < 0) then return 0;
int res = 1;
for (int Y = 1; Y <= Z; Y++)
{
res *= Y;
}
return res;
}
. 다른 팁
예 :
public int multiply(int Z)
{
int Y = Z;
for (int i = Z; i > 0; i--)
{
Y *= i;
}
return Y;
}
.
램다스를 이용한
계승 :
Func<int, int> factorial = null;
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
var result = factorial(10);
.
: -)
public int multiply(int Z)
{
int result = Z;
for (int i = 1; i <= Z; i++)
{
int Z*=i;
}
return Z;
}
. 제휴하지 않습니다 StackOverflow