1008: Series summation

1008: Series summation

Problem description: Known: Sn= 1+1/2+1/3+…+1/n. Obviously for any integer K, when n is large enough, Sn is greater than K. Now given an integer K (1<=k<=15), it is required to calculate a minimum n; making Sn>K.

Input: keyboard input k

Output: screen output n

Sample input: 1

Sample output: 2

Tip: Pay attention to accuracy issues and use double

Code:

Method 1: for loop, break to jump out

#include<stdio.h>
int main()
{
    double Sn=0,i;
    int k,n;
    scanf("%d",&k);
    for(i=1;;i++)
    {
        Sn+=1/i;
    if(Sn>k)
    {
        n=i;
        break;
    }
    }
    printf("%d",n);
}

Method 2: while loop, conditional jump out

#include <stdio.h>
int main()
{
    int k, n = 1;
    double Sn = 0;
    scanf("%d", &k);

    while(Sn <= k)
    {
        Sn = Sn + 1.0/n;
        n++;
    }
    printf("%d\n", n-1);
     
    return 0;
}

Analysis: Pay attention to the size of the output n, whether it is reduced by one


Guess you like

Origin blog.csdn.net/m0_61409069/article/details/126193216