求和和求平均值在不同的编程语言中有一些差异,下面分别给出几种常见编程语言的实现方法:
Excel VBA
在Excel VBA中,可以使用以下代码进行求和和求平均值:
求和
```vba
Public Sub dicSum()
Dim dicA As Object, i As Integer
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
Public Sub dicAvg()
Dim dicA As Object, dicB As Object, i As Integer
Dim total As Double, count As Double
' 用于保存结果
Set dicA = CreateObject("Scripting.Dictionary")
Set dicB = 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
dicB(Cells(i, 1).Text) = dicB(Cells(i, 1).Text) + 1
i = i + 1
Loop
total = 0
count = 0
For Each key In dicA.Keys
total = total + dicA(key)
count = count + dicB(key)
Next key
[G2].Value = total / count
Set dicA = Nothing
Set dicB = Nothing
End Sub
```
Python
在Python中,可以使用以下代码进行求和和求平均值:
求和
```python
numbers = [1.2, 3.4, 5.6]
total = sum(numbers)
print("总和为:", total)
```
求平均值
```python
numbers = [1.2, 3.4, 5.6]
average = sum(numbers) / len(numbers)
print("平均值为:", average)
```
Java
在Java中,可以使用以下代码进行求和和求平均值:
求和
```java
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int total = 0;
for (int num : numbers) {
total += num;
}
System.out.println("总和为: " + total);
}
}
```
求平均值
```java
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
double average = (double) total / numbers.length;
System.out.println("平均值为: " + average);
}
}
```
C语言
在C语言中,可以使用以下代码进行求和和求平均值:
求和
```c
include
int main() {
int numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("总和为: %d\n", sum);
return 0;
}
```
求平均值
```c
include
int main() {
int numbers = {1, 2, 3, 4, 5};
double average = (double) sum / 5;
printf("平均值为: %.2f\n", average);
return 0;
}
```
这些代码示例展示了如何在不同的编程