Mt. Moon Community

Full Version: Need C++ help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm taking a computer programming course, and I need help fixing a logic error. Note that the class was given a faulty program to correct. The program is supposed to swap the values of the two numbers imputed at the end, but the logic error causes it to display only the second value because it tells the computer to change one value first and then change the other value to the now changed first value.

Example:
a and b are values
a is now equal to b
b is now equal to a (but because a is equal to b, b is equal to b)

The following is the program code. I put the part that I believe contains the logic error in bold, but I do not understand how to correct it. I was not explained in class how to correct logic errors, but I still need to turn this in on Tuesday. So...if someone could help...thank you very much!

=====================================================

#include <iostream>
using namespace std;

int main()

{

float firstNumber;
float secondNumber;

// Prompt user to enter the first number.

cout << "Enter the first number" << endl;
cout << "Then hit enter" << endl;
cin >> firstNumber;

// Promt user to enter the second number.

cout << "Enter the second number" << endl;
cout << "Then hit enter" << endl;
cin >> secondNumber;

// Echo print the input.

cout << endl << "You input the numbers as " << firstNumber
<< " and " << secondNumber << endl;

// Now we will swap the values.

firstNumber = secondNumber;
secondNumber = firstNumber;


// Output the values.

cout << "After swapping, the values of the two numbers are "
<< firstNumber << " and " << secondNumber << endl;

return 0;

}
If you're needing to do what I think you are, you need to put a "temp" variable so that it stores the original number. Such as:

Code:
temp = secondNumber;
//temp stores the value of secondNumber

secondNumber = firstNumber;
//secondNumber becomes equal to the value of firstNumber

firstNumber = temp;
//firstNumber becomes the value of temp, which is storing secondNumber

I'm not entirely sure. It will probably do it. My C++ isn't terribly top notch. Toungue
Ah, that worked. I just had to put in the temp at the beginning of the block after putting in what you said for it to work.

Thank you very much again!

...oh, and could you lock this thread?
You're welcome. I actually had to do a similar exercise in QBASIC (and later Visual Basic) so I figured it would be a very similar process to begin with.
Reference URL's