编写递归函数求1+2+3+……+n的值,并显示结果

来源:百度知道 编辑:UC知道 时间:2024/06/25 01:34:36

Private Sub Command1_Click()
Dim n As Long
n = Val(InputBox("请输入n的值", , 100))
Print "1+2+3+……+"; n; "的值为:"; SumN(n)
End Sub
Private Function SumN(n As Long) As Long'递归函数
If n = 1 Then
SumN = 1
Else
SumN = SumN(n - 1) + n
End If
End Function

int fun(int n)
{
if( n == 1)
return 1;
else
return n + f(n-1);

}

int Sum(int n)
{
if(n==1) return 1;
n=Sum(n-1)+n;
return n;
}
main()
{
int a;
scanf("%d",&a);
printf("%d\n",Sum(a));
}
//结果:
Sum(a)
press any key to continue

准备一个按纽,代码如下
Option Explicit: Dim n As Integer, i As Integer, s As Integer

Private Sub Command1_Click()
s = 0
n = InputBox("请输入n的值")
For i = 1 To n
s = s + i
Next i
Print "1+2+3+……+n的值为:&quo