0

I have a code which should check the number before and after the comma. If these numbers are equal, the program writes out '1', otherwise - '0'.

float num, pnum;
std::cout << "num = ";
std::cin >> num;
pnum = num - int (num);
for (int i = 0; i < 7; i++) {
    pnum = pnum * 10;
}
while (int (pnum) % 10 == 0) {
    pnum = pnum / 10;
}
if (int (num) == int (pnum)) {
    std::cout << "1\n";
} else {
    std::cout << "0\n";
}

Results:

num = 2.2
output = 1
num = 22.22
output = 0

why?

note: I don't want to use strings in this program

np.
  • 109
  • 1
  • 11
  • They probably are not equal for the same reason why 0.1 + 0.2 is not equal to 0.3 – drescherjm May 05 '22 at 19:27
  • Floating point numbers cannot represent all real numbers. For example, 22.22 might not fit exactly and instead be stored as a close enough 22.219999999. – user4581301 May 05 '22 at 19:27
  • 1
    Use a string for your input instead of a floating point type. – NathanOliver May 05 '22 at 19:28
  • 1
    floating point numbers not being exact aside your code would also consider `2.002` as a yes / 1. Not sure if thats intended – 463035818_is_not_an_ai May 05 '22 at 19:30
  • _"note: I don't want to use strings"_ You also don't want to use `float`, as you are inspecting decimal values and float typically doesn't store decimals. – Drew Dormann May 05 '22 at 19:31
  • *note: I don't want to use strings* -- Well, if you cannot use a third-party fixed-point library, your only choice is to use strings. – PaulMcKenzie May 05 '22 at 19:45
  • @PaulMcKenzie what library do you mean? – np. May 05 '22 at 20:14
  • @np A library that does exact math on both sides of the decimal point. Using `float` or even `double` will not give you this. Right now, your out-of-the-box option is limited to only using strings, and parsing the string on both sides of the `'.'` character into two integer values. Also, who gave you this assignment? Whoever gave it to you must have been aware of the issues using floating point. If they were aware and now you're stuck, maybe the point of giving you the assignment was to see for yourself that floating point is not exact. – PaulMcKenzie May 05 '22 at 20:54

0 Answers0