1

I'm beginner in using functions, and I wrote this simple code. But I don't know why the volume is always calculated as zero.

 #include <iostream>
 using namespace std;

 double area (double) ;
 double volume (double) ;
 int main () {
     double radious ;
     cout << "please enter the Radious \n" ;
     cin >> radious ;
     cout << "The area = " << area(radious) << "\n" ;
     cin >> radious ;
     cout << "The volume = " << volume(radious) << "\n" ;
     cout << radious << "\n" ;
 }

 // defintion function of the area 
 double area (double R) {
     return ( (4) * (3.14) * (R * R) ) ;
 }

 // defintion function of the volume 
 double volume (double R) {
     return ( (3/4) * (3.14) * (R * R * R) ) ;
 } 
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Halemoo
  • 11
  • 3
  • 5
    [Please do not post images of code because they are hard to use.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) Code should be posted directly **as text** in your question. – MikeCAT Nov 22 '20 at 14:22
  • 2
    Include the code in the question, don't post pictures. `3/4` is `0`, and `0` multiplied by anything is `0`. – Eljay Nov 22 '20 at 14:22
  • 5
    `(3 / 4)` is zero because this is integer division. – MikeCAT Nov 22 '20 at 14:22
  • 1
    Does this answer your question? [Why does this calculation (division) return a wrong result?](https://stackoverflow.com/questions/41827246/why-does-this-calculation-division-return-a-wrong-result) – Raymond Chen Nov 22 '20 at 14:57

2 Answers2

0

Your function volume will always return zero because 3 divided by 4 is 0 when interpreted as an integer. This is because casting any real value to integer will simply result in discarding decimal part. For example, 2.7 as int will be 2 not 3, there is no rounding, in a mathematical sense.

You can fix this in 2 ways:

A) reorder your equation so division will be the last operation you do, e.g. ((3.14*R*R*R*3)/4). Note that this is often necessary, when you want your result to be int, which is not the case here.

B) explicitly say that either (or both) 3 or 4 have to be treated as a real number (float/double) by adding .0, e.g. 3.0/4 or 3/4.0 or 3.0/4.0. This approach is better in your case since you expect double anyway.

For more information refer to Numeric conversions and this FAQ

NRUB
  • 404
  • 4
  • 17
0

The part 3/4 in your code performs an integer division. Integers cannot have floating points so usually the last part of integer is truncated, which leaves 0 in your case.

You can replace 3/4 with 3.0/4.0to make it work.

Good Luck!

saadurr
  • 57
  • 10