01-27-2008, 05:06 PM
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;
}
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;
}
