Help with floating point number.

I created a program to print the sum of the values implemented on myFirstFunction as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <cstdlib>
#include <iostream>

using namespace std;

int myFirstFunction(int value1, int value2)
{
      return value1 + value2;
}      

int main()     
{            
      int value = myFirstFunction(1, 10);
      cout << value;
      system("PAUSE");
      return 0;
}


The output shows 11Press any key to continue.

If I want to divide value1 between value2 (to get 1/10 = 0.1) the program only prints out 0.

How can I use a floating point function to make the program show 0.1?

Thanks in advance
Use type double instead of int
at lines 6 and 13.

Also, it doesn't matter here as the conversion will be automatic, a value such as 10 is considered an integer, while 10.0 is a floating-point value.

See tutorial page:
http://www.cplusplus.com/doc/tutorial/variables/
Thanks a lot Chevril. I've written again the program and it ran successfully.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include <cstdlib>
#include <iostream>

using namespace std;

float myFirstFunction(float value1, float value2)
{
      return value1 / value2;
}      

float main()     
{            
      float value = myFirstFunction(1, 10);
      cout << value;
      system("PAUSE");
      return 0;
}
The function myFirstFunction() looks ok. Well done.

However float main() is an error. I'm surprised your compiler accepted it. Usually we want to set the compiler to tell us about such errors.
main() must always return a type int.
int main()


Also, it's fair to regard type float as for specialist use (perhaps when you need to store a really huge number of floating-point values). It occupies less space and is less accurate than type double which should be regarded as the default type whenever you need floating-point numbers.

Here's the value 1/3 calculated using types long double, double and float respectively.
0.33333333333333333334
0.33333333333333331
0.33333334


try this:
1
2
3
4
5
      cout << fixed << setprecision(20);
      cout << "long double: " << 1.0L / 3.0L << '\n';
      cout << "double:      " << 1.0  / 3.0  << '\n';
      cout << "float:       " << 1.0f / 3.0f << '\n';
      cout << "int:         " << 1    / 3    << '\n';
Last edited on
Topic archived. No new replies allowed.