C语言求一个数组两两的差值
时间: 2024-09-25 12:12:40 浏览: 45
C语言中判断两数组中是否有相同的元素
在C语言中,如果你有一个整数数组,想要计算每对相邻元素之间的差值,你可以通过遍历数组并逐个减去前一个元素来实现。这里是一个简单的示例:
```c
#include <stdio.h>
// 定义数组和其大小
int arr[] = {5, 10, 15, 20, 25};
int n = sizeof(arr) / sizeof(arr[0]);
// 函数来计算差值并打印
void calculate_diff(int *arr, int n) {
for (int i = 1; i < n; i++) {
int diff = arr[i] - arr[i - 1];
printf("Diff between %d and %d is: %d\n", arr[i - 1], arr[i], diff);
}
}
int main() {
calculate_diff(arr, n);
return 0;
}
```
这个程序会计算数组`arr`中每个元素与其前一个元素的差,并依次打印出来。例如,对于输入{5, 10, 15, 20, 25},它会输出:
```
Diff between 5 and 10 is: 5
Diff between 10 and 15 is: 5
Diff between 15 and 20 is: 5
Diff between 20 and 25 is: 5
```
阅读全文