Solved

c++ POW function

Posted on 2011-09-08
6
693 Views
Last Modified: 2012-08-14
Hello, i been trying to write my own pow function but it's not working out.. when i enter "base 2, power 3" gives me 4... not sure what my problem is..

#include <iostream>
using namespace std;

int CalcPower(int base, int power)
{

int total;

for (int i =0; i<power; ++i)
{
     total = base * base;
	 return total;
}
 
	
}
int main(void)
{

	int one;
	int two;

cout <<"please type in your base" <<endl;
cin >> one;
cout <<"please type in your power" <<endl;
cin >> two;
CalcPower(one,two);
cout<<endl;
cout << CalcPower(one,two);
}

Open in new window

0
Comment
Question by:businessesatoz
6 Comments
 
LVL 6

Accepted Solution

by:
effes earned 400 total points
Comment Utility
Hi,

you have your return statement inside the loop, so it returns just at he end of the first iteration.
Also you simply assign to total the value of base * base. Given that base is 2 this will always be 4 no matter how often you iterate through the loop.
You should also check wether power is 0 or 1. If it's 0 the return value is always 1 and if it's 1 then the return value is base istself.

Change your code to:

int CalcPower(int base, int power)
{
    if(power == 0)
    {
        return 1;
    }

    int total = base;

    for (int i =2; i<=power; ++i)
    {
        total = total * base;
    }

    return total;
}

Open in new window


Hope that helps,
Frank
0
 

Author Comment

by:businessesatoz
Comment Utility
Thanks for your help, although i have a question regarding
 int total = base; 

Open in new window

can't i just write
 int total; total = base * base

Open in new window

is that the same thing your doing here..? thanks
0
 
LVL 6

Expert Comment

by:effes
Comment Utility
you could write
int total;
total = base;

Open in new window

instead of
int total = base;

Open in new window

In the first snippet the variable total is first declared and then initialized.
In the second snippet this is done a single step.
BUT: base is not the same as base * base!

I'll try to explain the code I gave you in my first post:

This checks if power is 0. If so the result is per definition 1, so we can just return that.
if(power == 0)
{
    return 1;
}

Open in new window

The next step is to declare the variable we will use to calculate the result.
Since we already handled the case that power is 0 with the code above we can assume that power is at least 1. As base^1 is just base we can use this value to initialize total.
int total = base;

Open in new window

Now for the loop. If power is 1 the variable total already holds the correct result, so we don't have to enter the loop. That's why i starts at 2. If power is 2 or higher it will enter the loop an multiply the product of previous iterations (held in total) by base.
for (int i =2; i<=power; ++i)
{
    total = total * base;
}

Open in new window

At the end we simply have to return the value stored in total and we're done.
return total;

Open in new window

Just walk it through with power = 3:
power is != 0, so we initialize total = base
no the loop: i = 2 which is <= 3
total becomes total * base which equals base * base
next step: i = 3 which is <= 3
total becomes total * base which equals base * base * base
next step: i = 4 which is > 3
the loop is exited and total is returned as the result
total is now base * base * base which is base^3.

I hope that cleared things up a bit,
Frank
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 7

Assisted Solution

by:Murugesan Nagarajan
Murugesan Nagarajan earned 50 total points
Comment Utility
Updated code:

#include <iostream>
using namespace std ;

/*
        Compile time options on Linux:
                g++ -Wall fileName.C
        Remove the warning messages during compilation.
*/



/*
        Add comments here for describing the function CalcPower and the parameters.
*/
int CalcPower( int base, int power)
{
        /* int total ; Initialize all variables at the definition location. (To resolve the valgrind reported issues) */
        int total = 0 ;
        for ( int i =0 ; i < power ; ++i)
        {
                /* total = base * base ; */
                total += base * base ; /* Replace = with += */
                /* return total ; This needs to be added at the end of this function */
        }
        /* warning: control reaches end of non-void function */
        /* Hence write the following statement */
        return total ; /* Always use return for each functions */
}



/*
        Add comments here for describing the function main and the parameters.
*/
int main( void)
{
        /* int one ; Initialize all variables at the definition location. (To resolve the valgrind reported issues) */
        /* int two ; Initialize all variables at the definition location. (To resolve the valgrind reported issues) */
        int one = 0 ;
        int two = 0 ;
        cout << "please type in your base" <<endl ;
        cin >> one ;
        cout << "please type in your power" <<endl ;
        cin >> two ;
        CalcPower( one, two) ;
"calPow.C" 50 lines, 1611 characters
bectest2@aix52 /develop/bectest2/.Murugesan/tcp  [ 0 ]
$ mk
make: 1254-004 The error code from the last command is 2.


Stop.
xlC -g calPow.C
^[/bectest2@aix52 /develop/bectest2/.Murugesan/tcp  [ 0 ]
$ cat calPow.C
#include <iostream>
using namespace std ;

/*
        Compile time options on Linux:
                g++ -Wall fileName.C
        Remove the warning messages during compilation.
*/



/*
        Add comments here for describing the function CalcPower and the parameters.
*/
int CalcPower( int base, int power)
{
        /* int total ; Initialize all variables at the definition location. (To resolve the valgrind reported issues) */
        int total = 0 ;
        for ( int i =0 ; i < power ; ++i)
        {
                /* total = base * base ; */
                total += base * base ; /* Replace = with += */
                /* return total ; This needs to be added at the end of this function */
        }
        /* warning: control reaches end of non-void function */
        /* Hence write the following statement */
        return total ; /* Always use return for each functions */
}



/*
        Add comments here for describing the function main and the parameters.
*/
int main( void)
{
        /* int one ; Initialize all variables at the definition location. (To resolve the valgrind reported issues) */
        /* int two ; Initialize all variables at the definition location. (To resolve the valgrind reported issues) */
        int one = 0 ;
        int two = 0 ;
        cout << "please type in your base" <<endl ;
        cin >> one ;
        cout << "please type in your power" <<endl ;
        cin >> two ;
        CalcPower( one, two) ;
        cout << endl ;
        cout << CalcPower( one, two) ;
        cout << endl ;
        return 0 ; /* Always use return for each functions */
}

Open in new window

0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 50 total points
Comment Utility
that returns power*base*base
0
 

Author Closing Comment

by:businessesatoz
Comment Utility
thank you very much.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now