Please help with code!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

const double PI = 3.14159265358979323846;

struct Cone
{
    double height, radius;
};

void input (double height, double radius);
void setUp (double height, double radius, Cone* ptr);
double getVolume(Cone* ptr);
void output(Cone* ptr);

int main()
{
    Cone* ptr;
    double height, radius;
    ptr = new Cone;
    input(height, radius);
    setUp(height, radius, ptr);
    output(ptr);
    delete ptr;
}

void input(double height, double radius)
{

    cout << "Height: ";
    cin >> height;
    cout << "Radius: ";
    cin >> radius;

}

void setUp (double height, double radius, Cone* ptr)
{

    ptr->height = height;
    ptr->radius = radius;

}

double getVolume(Cone* ptr)
{
    return PI*(ptr->radius)*(ptr->radius)*ptr->height/3;
}

void output(Cone* ptr)
{
    cout << "Height: " << ptr->height << "Radius: " << ptr->radius << "Volume: " << getVolume(ptr);
}


after getting in radius and height
it becomes a scientific number
for example if i put in 1 and 2
it gives

Height: 1
Radius: 2
Height: 2.80515e-307Radius: 1.93613e-307Volume: 0

any idea?
When you pass a variable that isn't a pointer to a function (your input function, line 31), you can't actually make changes to that variable from within that function. The reason why your program doesn't work is that the input function doesn't actually change the values of height and radius. What you can do is merge input and setUp into a single function. That way, you can remove height and radius from your main() function, reduce the variables passed to setUp to just the pointer to an object of type Cone, and have it actually work.
thank you for your help.
but i am required to have those variables height and radius
+ input function... :(
but like Ispil says you arent storing the height and radius values at the end of your input function.
'height' & 'radius' inside your input method are in effect local variables. You can see this is you put a breakpoint on line 26 and examine the values of height and radius here. You'll see that you are pushing garbage values into your setup function.

You need to pass them by reference:
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

in this way you will actually alter the variables.

edit:
in fact, my compiler doesn't build your program unless i make said variables references:

source.cpp(24): error C4700: uninitialized local variable 'radius' used
source.cpp(24): error C4700: uninitialized local variable 'height' used

Last edited on
Topic archived. No new replies allowed.