Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2c52c3c

Browse files
authored
添加 58. 区间和 C语言版本
1 parent 830caef commit 2c52c3c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎problems/kamacoder/0058.区间和.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,45 @@ if __name__ == "__main__":
263263
main()
264264

265265
```
266+
### C
267+
268+
```C
269+
#include <stdio.h>
270+
#include <stdlib.h>
271+
272+
int main(int argc, char *argv[])
273+
{
274+
int num;
275+
// 读取数组长度
276+
scanf("%d", &num);
277+
278+
// 使用动态内存分配而不是静态数组,以适应不同的输入大小
279+
int *a = (int *)malloc((num + 1) * sizeof(int));
280+
281+
// 初始化前缀和数组的第一个元素为0
282+
a[0] = 0;
283+
284+
// 读取数组元素并计算前缀和
285+
for (int i = 1; i <= num; i++)
286+
{
287+
int mm;
288+
scanf("%d", &mm);
289+
// 累加前缀和
290+
a[i] = a[i - 1] + mm;
291+
}
292+
293+
int m, n;
294+
// 循环读取区间并计算区间和,直到输入结束
295+
// scanf()返回成功匹配和赋值的个数,到达文件末尾则返回 EOF
296+
while (scanf("%d%d", &m, &n) == 2)
297+
{
298+
// 输出区间和,注意区间是左闭右开,因此a[n+1]是包含n的元素的前缀和
299+
printf("%d\n", a[n+1] - a[m]);
300+
}
301+
302+
// 释放之前分配的内存
303+
free(a);
304+
return 0;
305+
}
306+
307+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /