Home > Software design >  Is there a way to make a function for calculating 10 to the x exponent in C? "ten_to_the(x expo
Is there a way to make a function for calculating 10 to the x exponent in C? "ten_to_the(x expo

Time:10-26

First post!!! Hi everyone, so I need to multiply a number by 10 to the (x) power, depending on the exponent I may require. I know there is a function, in the <math.h> library, but I was wondering if I could make my own function to achieve basically the same but only for 10, not any number; It´s for a course homework but since we haven´t been told about this library, I want to try to achieve it without said power() function.

Here's my code, it does compile, but I get some weird number instead of the intended 5000.

#include <cs50.h>
#include <stdio.h>

int ten_to_the(int n);

int main(void) {
    int x = 50;
    x *= ten_to_the(2);
    printf("%.i\n", x);
}

int ten_to_the(int n) {
    n = 1;
    for (int i = 0; i < n; i  ) {
        n *= 10;
    }
    return n;
}

CodePudding user response:

Because you multiple n by 10 on each iteration of the loop, i < n can never become true. In practice, n keeps getting bigger until it overflows and becomes negative.

Use another variable to keep track of the result separate from the number of iterations you need to calculate.

Instead of this:

int ten_to_the(int n)
{
    n = 1;
    for (int i = 0; i < n; i  )
    {
        n *= 10;
    }
    return n;
}

This:

int ten_to_the(int n)
{
    int result = 1;
    for (int i = 0; i < n; i  )
    {
        result *= 10;
    }
    return result;
}
  •  Tags:  
  • c
  • Related