0

When I run the result is zero, except for -5. I checked, it has nothing to do with the last line.

#include <iostream>
using namespace std;

int main ()
{
    int x;
    float E;
    cin >> x;
    if((float)x!=-5)
    {
        E=(x+3)/(x+5);
        cout << "Valoarea expresiesi este: " << E;
    }
    else 
        cout << "You cannot divide by zero";
    cin.get();
    return 0;
}

What did I miss? Thank you.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Tamás
  • 167
  • 9
  • 12
    Look up *integer division*. You are dividint two ints. If the magnitude of the denominator is larger than that of the numerator you get `0`. There are SO duplicates around. – juanchopanza Jan 10 '14 at 08:53
  • 2
    This doesn't always return `0`. Try feeding this `-6`. – user2357112 Jan 10 '14 at 08:56
  • [Another duplicate on integer division](http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c) – Mike Jan 10 '14 at 12:20

4 Answers4

2

(x+3)/(x+5) is evaluated as an integer division, which rounds toward zero. It doesn't matter that E is a float, because neither x+3 nor x+5 is a float. As you've written it, the conversion to floating-point will happen after the rounding has already occurred. Convert an operand to floating-point before performing the operation:

E = (1.0*x+3) / (x+5);
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • And how can I specify the number of decimal places? f2.22E doesn't work. – Tamás Jan 10 '14 at 09:02
  • @Tamás: I have no idea what `f2.22E` is supposed to be. In C, we'd use `printf` with a format specifier indicating 2 decimal places. I dunno about C++. – user2357112 Jan 10 '14 at 09:03
  • OK. I'm in college and they are supposed to be teaching me c++ and we used the above format specifier along with printf – Tamás Jan 10 '14 at 09:18
2

You are dividing two integers and the result will be zero since the denominator is larger. To simply solve this, use 3.0 and 5.0 as your literals.

E = (x + 3.0) / (x + 5.0);
Zeta
  • 103,620
  • 13
  • 194
  • 236
It'sPete
  • 5,083
  • 8
  • 39
  • 72
1

For any x > -5, (x+3)/(x+5), the denominator will always be greater than numerator and the integer division will always return 0. Only if you provide x < -5 the answer will never be 0.

kvivek
  • 3,321
  • 1
  • 15
  • 17
0

Don't ever compare floats/doubles with strict comparisson == nor !=. What you should do is

if ( fabs(x-5) < 0.00001 ) { // logically x == 5
}
else {
}

EDIT

Check also my post about infinite loop

Community
  • 1
  • 1
SOReader
  • 5,697
  • 5
  • 31
  • 53
  • 1
    This doesn't answer the question. Also, `x` is an integer, so using a tolerance for the comparison is pointless. – user2357112 Jan 10 '14 at 09:20
  • I know but it looks like he's beginning his journey with C++ so I wanted him to know about floating point numbers comparison. – SOReader Jan 10 '14 at 09:21