I am suposed to use the abs function and keep a loop going while a person enters
ID: 3530901 • Letter: I
Question
I am suposed to use the abs function and keep a loop going while a person enters numbers 1 at a time. When the difference from the last number entered is equal to or greater then it couts and ends the program. I have everything working except when I enter -10 and 10 it ends it. Shouldn't it keep going since -10 with the abs function equals 10? here is my code
#include <iostream>
#include <cmath>
using namespace std;
int diff( int , int );
int main()
{
int numb1, numb2;
cout << "Enter Some Numbers " << endl;
cin >> numb1 >> numb2;
while ( diff ( numb1,numb2 ))
{
numb1 = numb2;
cin >> numb2;
}
cout << "The difference is greater than or equal to 10" << endl;
return 0;
}
int diff ( int num1, int num2 )
{
intdifference = num1 - num2;
if ( abs ( difference ) < 10 )
{
return true;
}
else
{
return false;
}
}
Explanation / Answer
//I think you are confused. As is, 10 and -10 differs by 20, not 0. if you want it to equal 0, you'll have to take abs of num1 and num2 before taking its difference
//like this:
#include <iostream>
#include <cmath>
using namespace std;
int diff( int , int );
int main(){
int numb1, numb2;
cout << "Enter Some Numbers " << endl;
cin >> numb1 >> numb2;
while ( diff ( numb1,numb2 )){
numb1 = numb2;
cin >> numb2;
}
cout << "The difference is greater than or equal to 10" << endl;
return 0;
}
int diff ( int num1, int num2 ){
double difference = abs((double)num1) - abs((double)num2);
if ( abs ( difference ) < 10 ){
return true;
}
else{
return false;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.