Hey Guys I am new to C++, And for the past hour I have been trying to create a program that calculates the powers of any two numbers the user gives... For example if I input 5 and 5, I should get the result of 5^5...which is 3125. This is what I wrote so far...
#include <iostream>
// double exponet(double base, double power);
usingnamespace std;
int main()
{
int base, power, answer; // Variables
cout << "Please input a number... " << endl;
cin >> base;
cout << "Please input a power to bring said number: " << endl;
cin >> power;
for (int i = 1; i <= power; i++) // While i is less then the power, multiple the base times its self.
{
answer = (base * base);
}
cout << answer;
}
It does not work though, Ever time I input a number I get that number JUST times its self... I think I know what the problem is but I am not sure... Can any one please help...
I'm not sure what you mean, your code will be exactly the same the only thing that changes is your actual calculation. You can't leave your code exactly the way it is now, because it doesn't work.. :p
#include <iostream>
#include <string>
// double exponet(double base, double power);
usingnamespace std;
int main()
{
int base, power, answer=1; // Variables
string q;
cout << "Please input a number... " << endl;
cin >> base;
cout << "Please input a power to bring said number: " << endl;
cin >> power;
for (int i = 1; i <= power; i++) // While i is less then the power, multiple the base times its self.
{
answer = (answer * base);
}
cout << answer<<endl;
cout<<"Enter a character to exit.\n";
cin>>q;
}
It's good practice to initialize your ints to some default value, otherwise you'll end up with a garbage value if you don't initialize it before use. I think that's what happened when you got 153125.
Ohhh Ok, thank you...But I do not see how this works, it does work believe me...But can you explain how it works? I just dont want to go away with this without learning something!
In your code, when you enter your for loop for the first time you encounter answer = (answer * base); here you use answer, but it doesn't have a value yet. Because you didn't give answer a value, it is filled with some random number. Your program then uses that random number and that's why you should initialize answer to 1: int base, power, answer=1; so now, when you encounter answer = (answer * base); answer is initialized to 1 and you can safely use it to do multiplications.