Thread: PowerOf Function

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    13

    PowerOf Function

    Code:
    /* Title: c5 Review 9 (c05r09) */
    #include <iostream.h>
    
    // ----------------------------------------
    
    void Introduction()
    {
    IGNORE THIS PART
    }
    
    // ----------------------------------------
    
    double PowerOf(double x, int n)
    {
    CODE NEEDED HERE
    	return ();
    }
    
    // ----------------------------------------
    
    int main()
    {
    	double x;
    	cout << "Enter the base number: ";
    	cin >> x;
    
    	int n;
    	cout << "Enter the exponent: ";
    	cin >> n;
    
    	PowerOf(x, n);
    	return(0);
    }
    I need help figuring out how to get a number to a power and it displaying the results. What I mean is, I define x as 2 and say n as 3. That would be 2^3, or the number 8. Inside the PowerOf() function, I can't figure out the code to do that. I know it has something to do with a for loop though.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I can't figure out the code to do that.
    How would you do it on paper? Or with a calculator? Once you know that the code for such a simple function practically writes itself.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    13
    I know how to do it on the calculator, and on paper, I just can't get the for statement to give me what I want. It's probably a really simple 3-4 line code I'm just dancing around. Help?

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I just can't get the for statement to give me what I want
    ...
    Code:
    double PowerOf ( double base, int n )
    {
      double ret = 1.0;
    
      for ( int i = 0; i < n; i++ ) {
        ret *= base;
      }
      
      return ret;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM