Exponent using functions in a while loop

All works except once you do two numbers above 9 to the 9th in the while loop, so 10 to the 10th, it does an extra loop and gives the wrong input.

We are required to do a while loop to calculate and have separate functions for each part of the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

#include <iostream>

using namespace std;


//Create Function Prototypes: 
void iInput(int& num1, int& num2); //Used for the input of 2 integers
int MultiplyNumbers(int num1, int num2); //Used to Calculate the first to the power of the second and then output the result.
void DisplayTotal(); //Used to Display to then output the result


//Declare Variables:
int num1 = 0;
int num2 = 0;


int main() //main function
{
	iInput(num1, num2); //Calls for input

	DisplayTotal();


}//End main()


void iInput(int& num1, int& num2) //Function to take the 2 numbers from the user
{

	// The input of the 2 numbers
	cout << "Enter 2 numbers to get the power of the first to the second number: " <<endl;
	cin >> num1 >> num2;

} //End iInput()



// Function to Calculate first # power with second number using a while loop
int MultiplyNumbers(int num1, int num2)
{
	//declare variables
	int totalexp = 1;
	int i = 0;

		while (i < num2) //if i does not equal the second number then go thru loop again			   
		{ 
			//multiple first user number the number of times the second number is to get the exponent and get a total
			totalexp *= num1;

			//checking the math
			//cout << i << "  Counter  " << num1 << " Num1 " << num2 << "  Num2  " << totalexp << "  Total " << endl;

			i = i + 1; //Add one to the counter i	
		}//end while

	
	return totalexp; //return the total calculated in the loop

}//End multiplyNumbers()



 // The output of the answer
void DisplayTotal() //Function to display the output
{
	MultiplyNumbers(num1, num2); //provide the total for the power

	//checking the math
	//cout << "Numbers in display function  " << num1 << " <= NUM1  " << num2 << "  <= NUM2  " << endl;

	cout << "Total is: " << MultiplyNumbers(num1, num2) << endl; //print the power

	//Pause for output to be read
	cout << "Press Enter to Continue";
	cin.ignore();
	cin.get();

} //End DisplayTotal()
Sounds like you're overflowing on a signed 32-bit integer.


9^9        =    87420489
(2^32)/2-1 =  2147483647 <-- max signed 32-bit integer
10^10      = 10000000000

Try changing int to unsigned long long.

If you want arbitrary size, you'd have to look into a BigInteger library for C++.
long long is the magic! thank you so much I had changed it to long and that didn't work!
Topic archived. No new replies allowed.