Reputation: 53
I am writing a simple code to take a number and a power based off user input and square the number to that power using functions. While attempting to compile the code, though, I get multiple errors. here is the code:
#include <iostream>
using namespace std;
double power(double& n1, sq)
{
for (int i = 0; i < sq; i++) {
n1* n1;
}
return n1;
}
int main()
{
double power(double&);
double num1, square;
cout << "Enter a number IMMEDIATLY: ";
cin >> num1;
cout << "\nEnter a power: ";
cin >> square;
power();
cout << num1 << endl;
return 0;
}
Here are the errors that I am receiving:
||=== Build: Debug in practice (compiler: GNU GCC Compiler) ===|
|5|error: 'sq' has not been declared|
In function 'double power(double&, int)':|
|6|error: 'sq' was not declared in this scope|
|7|warning: statement has no effect [-Wunused-value]|
In function 'int main()':|
|22|error: too few arguments to function 'double power(double&)'|
|15|note: declared here|
|17|warning: unused variable 'ans' [-Wunused-variable]|
||=== Build failed: 3 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|
Any help or light shed on how to fix these errors would be much appreciated, for i have been stumped for quite sometime. Thank you!
edit: so I have parsed square as an int and initialized the variables into the power() (as you guys have said) but now the code produces the incorrect answer as the output (anything bigger than squaring the number produces incorrect output).
#include <iostream>
using namespace std;
double power(double& n1, int& sq) {
for (int i=2; i<=sq; i++) {
n1*=n1;
}
return n1;
}
int main()
{
double power(double& n1, int& sq);
double num1;
int square;
cout << "Enter a number IMMEDIATLY: ";
cin >> num1;
cout << "\nEnter a power: ";
cin >> square;
power(num1, square);
cout << num1 << endl;
return 0;
}
Upvotes: 0
Views: 634
Reputation: 479
To answer your second question, simply trace through the code with an example:
Let's say the inputs are
n1 = 3
sq = 3
We know that 3^3 = 27
, so lets see if we get that answer.
First, the operation n1 *= n1
is multiplying n1 by itself. For squaring alone, this is fine: 3*3 = 9
. But then you loop through it again, and n1
is now 9, so the code will compute 9*9 = 81
.
See if you can figure it out from here. Hint: you'll need another variable for storage.
Also, your return
statement is outside of your brackets for the power()
function. Though its working on its own because you passed &n1
in as a reference. Either remove the return statement altogether, or make a new variable in main that receives the value from power(). If you do the latter, remove the &
symbol and place the return statement within the power brackets. To get a better understanding of passing by reference vs. passing by value, see this link. Good luck!
Upvotes: 1