-8
#include <iostream>
using namespace std;
int exponent(int x){
    int n = 6;
    for (int i = 0 ;i<4 ;i++){
        n*=6;
    }
    return x;

}
void print_exponent(int x){

    cout<<"6^5 = "<<x<<endl;
}
int main () {
    int x;

    print_exponent(x);
    return 0;
}

I wrote 2 functions, first one to calculate 6^5, second one to print the value, when I run this, it prints wrong calculation (28), What's wrong with this function?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Adam Eve
  • 9
  • 4

3 Answers3

4

Your exponent function needs to return the n instead of x and in your main() you probably want to initialize the variable x to the value of function exponent with an argument of 5:

int x = exponent(5);

prior to printing via:

print_exponent(x);

That being said, your exponent function is broken as the return value is always the same no matter the parameter value. Modify the for loop to be:

for (int i = 1; i < x; i++) {
    n *= 6;
}

And you probably want to check if the parameter is equal to 0:

if (x == 0) {
    return 1;
}
Ron
  • 14,674
  • 4
  • 34
  • 47
  • 1
    @AdamEve Certainly not. I am sorry but SO is not a code writing service. What I can do is try to point you in the right direction and do the debugging. The rest is up to you. – Ron Jan 23 '18 at 09:56
  • Okay, I don't understand int x = exponenet(5) , where should I write this? in main function or where? – Adam Eve Jan 23 '18 at 09:59
  • 1
    Please have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list to establish a frame of reference. – Ron Jan 23 '18 at 09:59
2

You never call exponent. Instead you print the uninitialized and indeterminate value of x.

Besides, your exponent function returns the argument x, but it never modifies or assigns to x.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Your exponent function is calculating with n and returns the unused x.
Besides that int x; needs to be initialized before calling exponent(x);

Maku
  • 199
  • 2
  • 15