I am very new to c++ and we cannot use any built in libraries yet for the following program.

The program runs fine until I add a question at the end if the user wants to quit or not. If not the program will run again to compute the power to another base number that is input by the user....and so on until they prompt to exit.

when I run it the first number input comes out fine. The next one that is input, the answer is added to the first answer....therefore being wrong.

Example:
"enter a positive integer"
3
"enter another integer as exponent"
2
9 /* 9 is correctly displayed */
"Do you want to continue"?
Y
"enter a positive integer"
2
"enter another integer..."
2
36 /* this is where it is coming out incorrect...the 4 is being mult by 9...*/

I have feeling its something very simple that I'm doing wrong...but i have gone around in circles trying to find whats wrong. I know you cannot give answers but any help in direction will be appreciated.

Here is my code:

#include <iostream>
using namespace std;

int main ()  {

   int x;  
   int y; 
   int pwr = 1;
   bool exit = false;   
   char YesNo;
  
   while (!exit) {

   cout << "Enter a positive integer: ";  
   cin >> x;
   cout << "Enter another integer as the exponent: "; 
   cin >> y;
  
   for (int i = 1; i <= y; i++) {
	   pwr = pwr * x;
	 }
   cout << pwr << endl;
   
  
   cout << "Do you want to continue? (Y or N) \n";
   cin >> YesNo;
 
   if (YesNo == 'N' || YesNo == 'n')
    exit = true;  
}

   system("pause");
   return 0; 
}

just reset pwr to 1, since pwr never goes out of scope it holds the old value

Thanks,
Will have to try after work tomorrow. I will let you know how it works.
thanks!

Yes, this was a very simple fix. Thank you for your responses. I just moved the pwr declaration inside the While loop and works just fine now.

Thank you!

This article has been dead for over six months. Start a new discussion instead.