-2

I have got a task to create a program that calculates the diameter of the sphere of volume 1234.67 cu meters.

I have Written the following code : -

#include <iostream>
#include <math.h>

using namespace std;

int main(){
    float vol, dm, h;
    vol = 1234.67;
    cout << "Calculating the diameter of sphere with volume 1234.67 cu meters" << endl;
    h = vol*(3/4)*(7/22);
    dm = 2 * cbrt(h);
    cout << "The diameter of sphere with volume 1234.67 cu meters is " << dm << endl;
    return 0;
}

What's wrong with my program , it gives 0 as the output

Calculating the diameter of sphere with volume 1234.67 cu meters                                                                                                             
The diameter of sphere with volume 1234.67 cu meters is 0 
Aditya ultra
  • 942
  • 1
  • 8
  • 15

4 Answers4

0

This is because 7/22 equals zero. Read about C's integer division here

You need to use floating point division if you intend to use floating point precision.

Community
  • 1
  • 1
mbomb007
  • 3,788
  • 3
  • 39
  • 68
0
h = vol*(3/4)*(7/22);
dm = 2 * cbrt(h);

3,4,7,22, and 2 are integers. Change them to floats or doubles (3.0, or 3.f for example). This should fix your problem.

hello_world
  • 442
  • 3
  • 7
0

You've used integer division everywhere, which disregards the floating part instead of rounding.

Use 3.f/4.f or 3.0/4.0 instead

KABoissonneault
  • 2,359
  • 18
  • 17
0
h = vol * (3 / 4) * (7 / 22);

should be

h = vol * (3.f / 4.f) * (7.f / 22.f);

as with int 3 / 4 == 0.

Jarod42
  • 203,559
  • 14
  • 181
  • 302