More basic practicing codes I'm afraid. I've made a little thing to double a number designated by the user but the actual text that should be showing (apart from "Enter x value: ") isn't appearing. I'm just getting "Enter x value: ", then when I input 5 I get 10 back on the next line. Any thoughts?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int doubleNumber(int x)
{
usingnamespace std;
cout << "Enter x value to be doubled: " << endl;
int x;
cin >> x;
return x * 2;
}
int main()
{
usingnamespace std;
int x = -1;
cout << "Double x is: " doubleNumber(x) << endl;
return 0;
}
#include <iostream>
int doubleNumber() // take useless int x away
{
usingnamespace std;
cout << "Enter x value to be doubled: " << endl;
int x; // if we had the variable x above, then this would be in error
cin >> x;
return x * 2;
}
int main()
{
usingnamespace std; // u may wanna define this in the global scope
// useless int, can be removed
cout << "Double x is: " << doubleNumber() << endl; // You forgot the '<<' operator in the middle.
return 0;
}
C++ Shell: http://cpp.sh/32t
Many useless stuff up there, I have removed them and also you missed a '<<' operator.
Global scope means visible to the entire translation unit. As you have it, usingnamespace std; is only visible within your functions. By putting it at line 2, you don't need to include it within each function.
You might also have done this, to make use of the x declared in main() by passing it as a parameter to the function. Note that the variable name used doesn't have to be the same in function doubleNumber() as in main()
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;
}