Written in C language, calculate and output the following polynomial value s=1+1/(1+2)+1/(1+2+3)+ ..1/(1+2+3...+50)

C/C++ language programming topic

Written in C language, calculate and output the following polynomial value
s=1+1/(1+2)+1/(1+2+3)+…1/(1+2+3…+50)

C language design programming code

#include <stdio.h>

int main() {
    
    
    double s = 0; // 初始化s的值为0
    int n = 0; // 初始化n的值为0
    for (int i = 1; i <= 50; i++) {
    
    
        n += i; // 累加n的值
        s += 1.0 / n; // 累加s的值
    }
    printf("多项式口值s为: %.2lf\n", s);
    return 0;
}

In this program, we first define two variables s and n, which are used to save the cumulative sum of the polynomial mouth value and denominator. Then, we use a for loop to iterate over all natural numbers from 1 to 50. In the loop, we first accumulate the value of n, that is, add the current natural number to n, and then add the value of 1 divided by n to s. Finally, we use the printf function to output the calculation result.

The output of this program is the value of the polynomial value s, rounded to two decimal places.
operation result
insert image description here

C++ design programming code

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    
    
    double s = 0; // 初始化s的值为0
    int n = 0; // 初始化n的值为0
    for (int i = 1; i <= 50; i++) {
    
    
        n += i; // 累加n的值
        s += 1.0 / n; // 累加s的值
    }
    cout << "多项式口值s为: " << fixed << setprecision(2) << s << endl;
    return 0;
}

In this program, we first define two variables s and n, which are used to save the cumulative sum of the polynomial mouth value and denominator. Then, we use a for loop to iterate over all natural numbers from 1 to 50. In the loop, we first accumulate the value of n, that is, add the current natural number to n, and then add the value of 1 divided by n to s. Finally, we use the cout stream to output the calculation results, and use the fixed and setprecision functions to retain two decimal places.

The output of this program is the value of the polynomial value s, rounded to two decimal places.

Guess you like

Origin blog.csdn.net/qq_55433305/article/details/130547851