How can I add the result value to the previous value?

Asked

Viewed 101 times

1

I’d like to know, res the value of the sequence and then print it? as for example, enter the value of N equal to 2 and achieve output value 2.5?

#include <stdio.h>

int main (void)
{
    int N,i;
    float res;

    scanf("%d", &N);
    for( i = 1 ; i <= N; i++)
    {
        res = (float)i/((N - i) + 1);
    }
    printf("%.4f\n", res);
    return 0;
}

1 answer

2


To do this, you can use the operator += (addition assignment) to accumulate the result and initialize the variable res. The code should look like this:

#include <stdio.h>

int main (void){
    int N, i;
    float res = 0;
    puts("Digite um valor: ");
    scanf("%d", &N);

    for( i = 1; i <= N; i++){
        res += (float)i/((N - i) + 1);
    }
    printf("%.2f\n", res); // 2.50
    return 0;
}

DEMO

Browser other questions tagged

You are not signed in. Login or sign up in order to post.