Problem with my second C++ attempt, and using variables
Hey using this code I always end up with the number 1, why is this.
#include <iostream>
using name开发者_如何学Gospace std;
int y;
int x = (y + 1);
int main()
{
cin >> y;
cout << x << endl;
return 0;
}
The line:
int x = (y + 1);
doesn't auto-magically tie the value of x
to be always y + 1
. Because you're setting it when y
is zero (as a file-level variable, y
is be initialised to 0) and never changing it, x
will be 1
. If you want x
to change with y
, you should set x
whenever y
changes, such as with this:
#include <iostream>
int y, x;
int main (void) {
std::cin >> y;
x = y + 1;
std::cout << x << std::endl;
return 0;
}
because at initialisation y probably is set to 0 and thus x = 0 + 1 = 1; you have to use a function for obtaining your desired behaviour like
int yPlusOne(int y) { return y + 1};
int main() {
cin >> y;
cout << yPlusOne(y) << endl;
return 0;
}
This is not how the C++ works at all.
You defined the y
variable, then the x
variable with some initial value. In the main
function, you load new value to y
, but x
stays unchanged. You need to write what to do with the value in y
, so put the line x = y + 1
between the lines with input and output:
#include <iostream>
using namespace std;
int y;
int x;
int main()
{
cin >> y;
x = y + 1;
cout << x << endl;
return 0;
}
精彩评论