Hello, in chapter 4 in the book Programming principles and practice using C++ I have to write a program that use a while loop and that each time around the loop reads two double, prints out the largest, the smallest and if they are equal.
I have no problem with this program but I can't understand how to modify it following the author : Change the program so that it writes out "the numbers are almost equal" after writing out which is the larger and the smaller if the two numbers differ by less than 1.0/100.
int main()
{
double a = 0;
double b = 0;
while (cin >> a >> b) {
cout << "first number is : " << a << "\nsecond number is : " << b << "\n\n";
if (a > b) {
cout << "the larger value is : " << a << "\n";
cout << "the smaller value is : " << b << "\n";
}
elseif (b > a) {
cout << "the larger value is : " << b << "\n";
cout << "the smaller value is : " << a << "\n";
}
else
cout << "The numbers are equal\n";
if (a - b < 1.0 / 100)
cout << "Numbers are almost equals";
}// end of while
The problem is that I don't know how to test if the numbers differ by less than 0.01 because my if statement doesn't work in any case. If I enter 2 and 1.99 It doesn't work, why ? I found people with the same problem but that have far more experience than me in programming, so I don't know why this statement doesn't work.Can you explain me why in a very simple way for a newbie ? Thank you
#include <iostream>
#include <cmath>
#include <algorithm>
int main()
{
constdouble EPSILON = 1.0 / 100 ;
double a = 0;
double b = 0;
while ( std::cin >> a >> b ) {
std::cout << "first number is : " << a << "\nsecond number is : " << b << "\n\n";
if( a == b ) // check this first
std::cout << "The numbers are equal\n";
else { // not equal
if ( a > b )
{
std::cout << "the larger value is : " << a << '\n';
std::cout << "the smaller value is : " << b << '\n';
}
else // a < b
{
std::cout << "the larger value is : " << b << '\n';
std::cout << "the smaller value is : " << a << '\n';
}
// http://en.cppreference.com/w/cpp/numeric/math/fabsconstdouble difference = std::abs( a - b ) ; // absolute value of difference
if( difference < EPSILON ) std::cout << "Numbers are almost equal\n" ;
} // not equal
}// end of while
}
#include <iostream>
#include <iomanip>
int main()
{
double a = 10.01 ;
double b = 10.00 ;
// this may not (is very unlikely to) give 0.01 as the result.
// it will be quite close to 0.01, but may not be exactly 0.01
// could be either a wee bit lower than 0.01 or a wee bit higher than 0.01
std::cout << std::fixed << std::setprecision(16) << a-b << '\n' ; // 0.0099999999999998
a = 100.01 ;
b = 100.00 ;
std::cout << a-b << '\n' ; // 0.0100000000000051
a = 1000.01 ;
b = 1000.00 ;
std::cout << a-b << '\n' ; // 0.0099999999999909
a = 1000000.01 ;
b = 1000000.00 ;
std::cout << a-b << '\n' ; // 0.0100000000093132
}