I'm new to C++ and doing a drill from the book Programming Principles and Practice using C++. I'm really confused why these if statements aren't working, the first two work but the second two don't for some reason. I would appreciate if someone could explain why the if statements for "The numbers are almost equal" and "The numbers are equal" aren't working.
#include "../../../std_lib_facilities.h"
int main()
{
double val1 = 0;
double val2 = 0;
cout << "Please enter two floating point values.\n";
while (cin >> val1 >> val2)
{
if (val1 < val2)
{
cout << "The smaller value is: " << val1 << "\n" << "The larger value is " << val2 << "\n";
}
if (val2 < val1)
{
cout << "The smaller value is: " << val2 << "\n" << "The larger value is " << val1 << "\n";
}
if (abs(val1 - val2) < 1.0 / 100.0)
{
cout << "The numbers are almost equal. \n";
}
if (val1 == val2)
{
cout << "The numbers are equal. \n";
}
}
}
When using the numbers .001 and .002 I'm only getting the output that "The smaller value is: 0.001" and "The larger value is 0.002". I want it to also tell me that "The numbers are almost equal". Which I think that this should but it does not. This puts me under the assumption that the if statement if (abs(val1 - val2) < 1.0 / 100.0) is not working.
Yea if (val1 = val2) was just a typo from changing it up so much and copying/pasting all the time trying to get it to work.
Yes that works as well as it worked when I used my #include "../../../std_lib_facilities.h" instead of
1 2
#include <iostream>
#include <cmath>
So I found some code that works sorta properly. While this works the book I'm using says for it to first write out which is smaller and larger AND THEN write that the numbers are almost equal if the differ by less than 1.0/100 and this says it in the opposite order.
#include "../../../std_lib_facilities.h"
int main()
{
double val1 = 0;
double val2 = 0;
cout << "Please enter two floating point values.\n";
while (cin >> val1 >> val2)
{
if (abs(val1 - val2) < 1.0 / 100.0)
{
cout << "The numbers are almost equal. \n";
}
if (val1 < val2)
{
cout << "The smaller value is: " << val1 << "\n" << "The larger value is " << val2 << "\n";
}
elseif (val2 < val1)
{
cout << "The smaller value is: " << val2 << "\n" << "The larger value is " << val1 << "\n";
}
else
{
cout << "The numbers are equal. \n";
}
}
}