help with variables

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>

using namespace std;

int main()
{

    float x1;
    cout << "please enter first line length : " << endl;
    cin >> x1;
    float y1;
    cout << "please enter second line length : " << endl;
    cin >> y1
    ;float z1;
    cout << "please enter second line length : " << endl;
    cin >> z1
    ;float rad = (.5)*(x1+y1+z1);
    cout << rad << endl;
    if((x1>0)){int x2 = rad-x1;};
    cout << "x" << x2 << endl;
    /* I want to make another variable like this one in python
    x1=int(input("first line length :"))
    if x1>0:
    x2=rad-x1 (rad is defined in python)
else:
    print("please enter positive number for the firs line length")
    however it says that x2 was not declared */


;return 0;
}
Last edited on
1
2
3
4
5
6
if ( 0 < x1 )
  { // scope "foo" begins
    int x2 = rad-x1;
  } // scope "foo" ends

cout << "x" << x2 << endl;

You introduce (declare) variable x2 within a local scope. Stuff declared within scope vanishes at the end of the scope.

You could have the printout within the scope, where the x2 exists

OR

Declare (and initialize) x2 before the if-statement:
1
2
3
4
5
int foo = 7;
if ( /*cond*/ ) {
  foo = 42;
}
// use foo 
Last edited on
It's the prompt that is automatically put in the box you type your question into when you create a new topic. Some people don't delete the text that's already there.
Topic archived. No new replies allowed.