c#分别使用for、while、do-while循环计算1!+2!+...+20!阶乘的和 15
展开全部
sum = 0;
for (i=1;i<=20;i++)
{
multiply = 1;
for (j=1;j<i;j++)
{
multiply = j*multiply;
}
sum += multiply;
}
for (i=1;i<=20;i++)
{
multiply = 1;
for (j=1;j<i;j++)
{
multiply = j*multiply;
}
sum += multiply;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
//计算阶乘的私有方法
private int jiecheng(int i){
if(i==1)
return 1;
else
return i*jiecheng(i--);
}
//for
private int sumjiechengByFor(int n)
{
int sum =0;
for(int i=1;i<=n;i++)
{
sum +=jiecheng(i);
}
return sum;
}
//while
private int sumjiechengByWhile(int n)
{
int sum =0,i=1;
while(i<=n)
{
sum +=jiecheng(i);
i++;
}
return sum;
}
//dowhile
private int sumjiechengByDoWhile(int n)
{
int sum =0,i=1;
if(i<=0) return 0; //参数应该大于0
do
{
sum +=jiecheng(i);
i++;
}while(i<=n);
return sum;
}
private int jiecheng(int i){
if(i==1)
return 1;
else
return i*jiecheng(i--);
}
//for
private int sumjiechengByFor(int n)
{
int sum =0;
for(int i=1;i<=n;i++)
{
sum +=jiecheng(i);
}
return sum;
}
//while
private int sumjiechengByWhile(int n)
{
int sum =0,i=1;
while(i<=n)
{
sum +=jiecheng(i);
i++;
}
return sum;
}
//dowhile
private int sumjiechengByDoWhile(int n)
{
int sum =0,i=1;
if(i<=0) return 0; //参数应该大于0
do
{
sum +=jiecheng(i);
i++;
}while(i<=n);
return sum;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询