Help understanding code

Can anyone tell me why this "code" is going to 0?

cout << "enter 2 values >" ;
int a = 2, b = 1;
if(a > b)
{
a = b;
b = a;
}
cin >> a;
cin >> b;
cout << b / a;


being the values (4,1)
Your code is full of problems, which is OK for a real beginner.
First if you choose to get the values of a and b from user input, then don't initialize them as you did on line 2.
Second, to swap the values of two variables, the most basic way is to create a temp variable to store the intermediate value.
Third, integer divisions will always round down to the nearest integer, and that's why 1 / 2 = 0.
closed account (zb0S216C)
First, you prompt the user for two integers but you never give them the opportunity to enter those values. Then, you declare both a and b (which I'm assuming is where the given values are stored) and initialize them to 2 & 1, respectively.

Second, in your if block, a attains the value of b. Then, for some reason, b attains the value of itself by querying the value of a (which is the same value as b). After that, you then give the user the opportunity to enter the values they want to work with. Unknown to the user, the swap has already being made prior to input. Regardless, the swap attempt fails and is ignored anyway. Instead, you divide the two given numbers.

Overall, you need to reseat and fix your swap as well as a program redesign.

Wazzak
Topic archived. No new replies allowed.