Still practicing basic code, wrote something to square a number inputted by the user, but some values (e.g. 5, 10, 11, 13, 15, 20) come out as the squared number -1, any help would be very welcomed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cmath>
usingnamespace std;
int squareNumber ()
{
cout << "Enter number to be squared: " << endl;
int x;
cin >> x;
return pow(x,2);
}
int main ()
{
cout << "Your number squared is: " << squareNumber () << endl;
return 0;
}
but some values (e.g. 5, 10, 11, 13, 15, 20) come out as the squared number -1
That's probably due to truncating the floating-point value when it is converted to an integer. Why does this matter? Well, the pow() function typically will calculate the logarithm of x, multiply that by the required power, and then calculate the antilogarithm. Thus the result may be approximate, such as 24.99999995 or something.
At any rate, all that number-crunching is a huge overkill when all that is required is to multiply x by itself.
Well you did a good job at making it awkward when you did
Your number squared is: Enter number to be squared: 10
100
I think it would look much more cleaner like
Please enter a number to be squared: 10
10 squared is 100
You could do this by something like:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
std::cout << "Please enter a number to be squared: ";
int numberToBeSquared = 0; //I prefer to initialize
std::cin >> numberToBeSquared; //also good to give good variable names
std::cout << numberToBeSquared << " squared is " << numberToBeSquared * numberToBeSquared << std::endl;
return 0;
}
Please enter a number to be squared: 10
10 squared is 100
Just to be awkward again though, why would something like this not work? It says numberToBeSuared was not declared in this scope.
#include <iostream>
using namespace std;
int squareNumber ()
{
cout << "Enter number to be squared: " << endl;
int numberToBeSquared;
cin >> numberToBeSquared;
return numberToBeSquared*numberToBeSquared;
}
int main ()
{
cout << numberToBeSquared << " squared is " << squareNumber () << endl;
return 0;
}
Declare the variable in main(), pass it to the function. return a result from that function.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int doubleNumber(int n)
{
return n * 2;
}
int main()
{
int x = 0;
cout << "Enter x value to be doubled: " << endl;
cin >> x;
cout << "Double " << x << " is: " << doubleNumber(x) << endl;
return 0;
}