Thread: Create a function that returns a higher power of a number each time - C

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    3

    Question Create a function that returns a higher power of a number each time - C

    Hello everyone and thank you for taking your time to read this post.


    I came across a rather confusing problem for me. I have been given a prototype of the function I am not allowed to change and it has to perform the following task:

    If we call the function three times with the number 2 as parameter, it should return 2,4,8(the exponents increase with each call). However, if we call it with another number, the exponent resets and starts back from one. For example: When we call the function three times with number 2 as the parameter, it returns.2,4,8. But after that, if we call it with a different number(say 5) the function should return 5,25,125. and so on. To summarize, the exponent count has to reset to 1 each time the function is called with a different number.

    Now here comes the catch: here's the prototype:

    Code:
    double power(double x)
    Note that I can't use pointers because I can't send a pointer as a parameter. I managed to do something like this:

    Code:
    double power(double x) {
      static int exponent = 1;
      return pow(x,exponent++);
    }
    But how do I reset the exponent back to 1 when the function is called with another number? And are static and global variables the only way to do this?


    Thanks once again!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,508
    Use another static local variable to record the previous value of x. If x differs from this static local, then you know that it is time to reset exponent.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 02-08-2019, 02:13 PM
  2. Replies: 2
    Last Post: 02-19-2015, 12:18 AM
  3. a function that returns the number of bytes of a file
    By paulovitorbal in forum C Programming
    Replies: 22
    Last Post: 05-15-2006, 06:01 PM
  4. function that returns time
    By arian in forum C++ Programming
    Replies: 1
    Last Post: 06-08-2005, 02:53 AM
  5. Replies: 4
    Last Post: 01-29-2005, 11:57 AM

Tags for this Thread