Broken tanh function

Hello guys! I dont really know what is that but with 3/10 it gives the incorrect output 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
  #include <iostream>
#include <cstdlib>
#include <cmath>
#include <clocale>
using namespace std;

int main()
{
	double bb = tanh(3/10);
	cout << bb;
	system("pause\n");
	return 0;
}

and with 0.3
1
2
3
4
5
int main()
{...
	double bb = tanh(0.3);
...
}

the correct output 0.291313 .
So my question is why doesnt it work with the first one?
Last edited on
In C++, an int divided by an int gives an int.

Run this code to discover what 3/10 gives you:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <clocale>
using namespace std;

int main()
{
        double three_over_ten = 3/10;
        cout << "three_over_ten = " << three_over_ten << '\n';
	double bb = tanh(three_over_ten );
	cout << bb;
	system("pause\n");
	return 0;
}
Thank you for your reply accoring to the http://cpp.sh/ and visual studio 2017 it gives the same wrong output((
No, it's the RIGHT, expected output.

You are doing this:
tanh(0);
The correct and expected output is zero.

You have made the mistake of thinking that in C++, 3/10 gives you 0.3. It does not.

In C++, 3/10 gives you 0 .

In C++, an int divided by an int gives you an int.
0.3 is not an int.
0 is.

Last edited on
Thank you for your help. I've understood the error in my main code
Registered users can post here. Sign in or register to post.