求和编程怎么写

时间:2025-01-24 18:31:53 网络游戏

求和编程可以通过多种方法实现,以下是几种常见的方法:

1. 使用C++编写

```cpp

include

using namespace std;

int main() {

int n, shu, jihe = 0, ouhe = 0, i;

cin >> n;

for (i = 0; i < n; i++) {

cin >> shu[i];

if (shu[i] % 2 == 0) {

ouhe += shu[i];

} else {

jihe += shu[i];

}

}

cout << "奇数之和: " << jihe << endl;

cout << "偶数之和: " << ouhe << endl;

return 0;

}

```

2. 使用VBA编写

方法一:使用字典求和

```vba

Sub dicSum()

Dim dicA As Object

Dim ArrKey, ArrItem

Set dicA = CreateObject("Scripting.Dictionary")

i = 2

Do Until Cells(i, 1).Text = ""

dicA(Cells(i, 1).Text) = dicA(Cells(i, 1).Text) + Cells(i, 3).Value

i = i + 1

Loop

ArrKey = dicA.Keys

ArrItem = dicA.Items

[E2].Resize(dicA.Count, 1) = Application.Transpose(ArrKey)

[F2].Resize(dicA.Count, 1) = Application.Transpose(ArrItem)

Set dicA = Nothing

End Sub

```

方法二:使用自动求和公式

```vba

Sub 快速求和统计()

Dim ws As Worksheet

Dim 最后一行 As Long

Set ws = ActiveSheet

最后一行 = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

For i = 1 To 10

If Application.WorksheetFunction.Count(ws.Range(ws.Cells(2, i), ws.Cells(最后一行, i))) > 0 Then

ws.Cells(最后一行 + 1, i).Formula = "=SUM(" & ws.Cells(2, i).Address & ":" & ws.Cells(最后一行, i).Address & ")"

ws.Cells(最后一行 + 1, i).Interior.Color = RGB(255, 255, 0)

End If

Next i

MsgBox "统计完成啦!"

End Sub

```

3. 使用Excel公式

方法一:使用SUMIF函数

```excel

=SUMIF(A1:A10, ">1000", B1:B10)

```

方法二:使用SUMIFS函数

```excel

=SUMIFS(C1:C10, A1:A10, ">1000", B1:B10, "北京")

```

4. 使用递归求和(C语言)

```c

include

int sum(int n) {

if (n == 0) {

return 0;

} else {

return n + sum(n - 1);

}

}

int main() {

int n;

printf("请输入一个整数n:");

scanf("%d", &n);

printf("1到%d的和是: %d\n", n, sum(n));

return 0;

}

```

5. 使用循环求和(C语言)

```c

include

int main() {

int n, i, sum = 0;

printf("请输入一个整数n:");

scanf("%d", &n);

for (i = 1; i <= n; i++) {

sum += i;

}

printf("1到%d的和是: %d\n", n, sum);

return 0;

}

```

这些方法涵盖了从基本的循环求和到使用高级函数和VBA宏的复杂求和场景。根据具体需求和编程环境,可以选择合适的方法进行实现。