HELP: can't perform divide math function

Hi all,

I'm new to c++ and I'm trying to write a simple divide function,for example 1 divided by 3 (1/3). Suppose is will give me 0.33333 value but then my program always returned 0 value. Below is my code:

1
2
3
4
5
6
7
8
distance ( double x, double y){
 double probability;

 probability = x/y;

return probability;

}


Hope you guys can give me some hints. Thanks.
Your function does not specify the return type. I think that's valid in C, but not C++. I'm not certain. Some compilers may not allow this.
Any way, when the type is not specified, int is assumed. converting double to int rounds down, so 0.333 becomes 0.
The solution is to change it to double distance ( ...
Ok, I got this working:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <fstream>
using namespace std;


double distance_( double x, double y)
{
	cout << x / y << '\n';
	return ( x / y );
}

int main()
{
	double a = 3;
	double b = 9;

	double c = distance_( a, b );

	cout << c << '\n';
   
	return 0;
}


I think you might have been declaring x and y, that were passed to the function, as int's?

Also, I changed the name of your function. When using namespace std, there are certain names/functions that are already defined and you may come across errors!

Try using the same function name and sending doubles to it, rather than int's. I just had errors compiling it!

You can get around this, but taking away using namespace std; and using std::cout etc.

Or you can use things like:
using std::cout

And then continue using cout without the need of std:: in front of it.

Hope you understand that, I read over it a few times, lol (:
Thank you guys..i will work on it.. :)
Topic archived. No new replies allowed.