## 页首HTML代码 ```html

实现函数的功能

数据结构

C语言--代码题

1.函数的功能是:根据以下公式计算s,计算结果作为函数值返回;n通过参数传入。

s=1 + 1/(1+2) + 1/(1+2+3) + ........... + 1/(1+2+3+...+n)

例如:若n的值为11时,函数的值为:1.833333

/********************************************************************************************************
 * file name:  2024-04-29C_demo.c
 *  author   :  tongyaqi1110@163.com
 *  date     :  2024/04/29
 *  function : 设计函数功能实现 s=1 + 1/(1+2) + 1/(1+2+3) + ........... + 1/(1+2+3+...+n) 
 *  note     :  None
 * 
 * Copyright (c)  2024   tongyaqi@163.com   All right Reserved
 * ******************************************************************************************************/
#include <stdio.h>

double calculateS(int n) {
    double sum = 0.0;
    int i, j, temp;
    
    for (i = 1; i <= n; i++) {
        temp = 0;
        for (j = 1; j <= i; j++) {
            temp += j;
        }
        sum += 1.0 / temp;
    }
    
    return sum;
}

int main() {
    int n;
    double result;
    
    printf("请输入n的值:");
    scanf("%d", &n);
    
    result = calculateS(n);
    
    printf("计算结果为:%lf\n", result);
    
    return 0;
}

image

posted @ 2024-04-29 21:29  一面小镜子  阅读(21)  评论(0)    收藏  举报