lex
lex

Reputation: 3

C error causing function constant return value

When I call getinfo() I get a constant value of 8 with a 1 digit value, 9 with a 2 digit value, 10 with a 3 digit value. and so on. In the function, the value is printed as expected, however when attempting to read the value in the main method, the value is as mentioned above.

Any ideas as to why this is happening?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <math.h>


int main(){
    float radius = 0;
    float height = 0;
    float cylvolume = 0;
    float spherevolume = 0;

    displaymyinfo();

    radius = getinfo();
    printf("\n r = %f", radius);

    height = getinfo();
    printf("\n h = %f", height);



    cylvolume = compute_cylinder_volume(radius, height);
    spherevolume = compute_sphere_volume(radius);


    printf("h = %f", height);

    printf("\n A cylinder with radius %f and height %f = %f cubic inches", radius, height, cylvolume);
    printf("\n Volume of sphere with radius: %f is %f cubic inches", radius, spherevolume);

    _getch();
    return 0;

}
int displaymyinfo(){
    printf("*********************\n");
    printf("*Info was here  *\n");
    printf("*and here*\n");
    printf("*even here     *\n");
    printf("*********************\n");
    return 0;
}

float getinfo(){
    float y = 0;
    do{
        printf("\n Enter a number: ");
        scanf("%f", &y);
    } while (y <= 0);

    printf("%f", y);
    return (y);
}

float compute_cylinder_volume(float r,float h){
    float vol = 0.0;
    vol = 3.14 * r * r * h;
    return vol;
}
float compute_sphere_volume(float rad){
    float vol = 0.0;
    vol = 4.0 / 3.0 * 3.14 * rad * rad * rad;
    return vol;
}

Upvotes: 0

Views: 58

Answers (1)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

The line

    radius = getinfo();

appears before the function getinfo() is defined. C, being the helpful language it is, will assume that you intend to define a function that returns an integer. The fact that you define it to return a float later will not deter it from this belief.

Add

float getinfo();

somewhere above main() (or move main() to the bottom).

Upvotes: 2

Related Questions