Power Building Exercise in C

Asked

Viewed 325 times

1

I’m starting to learn how to program, so forgive me any more silly mistakes. It’s a simple exercise, doing a C power by setting the base and exponential. Here’s my code:

#include <stdio.h>

int main () {

    int n = 0;
    float x = 0;
    int k = 1;
    float s = 0;
    scanf("%d", &n);
    scanf("%f", &x);

    do{
        if(k!=n){
            k = k + 1; 
            s = x*x + s;
        }
        else { s = x;
        }
    } while( k != n); 

    printf("%f", s);

return 0;

}

Question is that for some reason, from the second operation it multiplies the X as an integer, example:

2.1 3: He should give me 2.1*2.1*2.1 = 9.26

Instead he gives me 2.1*2.1*2 = 8.82

Does anyone have any idea why this is and how to fix it?

  • 1

    I believe your algorithm is wrong. You are making a sum of x 2.

  • An alternative is: float s=1; and replace your loop with: for (k=1; k<=n; k++) s *= x;.

  • why not use Pow?

1 answer

2


In the variable s, you should be multiplying x and not x*x. Besides, it shouldn’t be adding up anything (that + s).

Here is your revised program. It also works for negative whole powers:

#include <stdio.h>

int main() {
    int n = 0;
    float x = 0;
    int k = 1;
    float s = 1.0;
    scanf("%d", &n);
    scanf("%f", &x);

    if (n > 0) {
        for (int k = 0; k < n; k++) {
            s *= x;
        }
    } else if (n < 0) {
        for (int k = 0; k < -n; k++) {
            s /= x;
        }
    }

    printf("%f", s);

    return 0;
}

See here working on ideone.

In case you don’t know, s *= x amounts to s = s * x, the s /= x amounts to s = s / x and the k++ amounts to k = k + 1. The use of for is equivalent to that of while in this context, and once it is understood, it is simpler to evaluate mentally as to its correctness.

Browser other questions tagged

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