Home > Back-end >  In c programming when calling by reference, float value take zero value
In c programming when calling by reference, float value take zero value

Time:08-02

When I enter float value for r in circle, It always take zero value. area and perimeter of circle result is zero because r take zero value.

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void circle(float, float *, float *);
main()
{
    float radius, area, perimeter;
    printf("Enter radius:");
    scanf("%f",&radius);
    circle(radius, &area, &perimeter);
    printf("radius:%f area: %f, perimeter:%f ", radius, area, perimeter);
}
void circle(r, ar, per)
float r, *ar, *per;
{
    *ar =3.14*(r*r);
    *per =2*3.14*r;
}

CodePudding user response:

Seems you have incorrect function definition. This code will work:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

void circle(float, float *, float *);

int main()
{
    float radius, area, perimeter;
    printf("Enter radius:");
    scanf("%f",&radius);
    circle(radius, &area, &perimeter);
    printf("radius:%f area: %f, perimeter:%f ", radius, area, perimeter);
    return 0;
}

void circle(float r, float *ar, float *per)
{
    *ar =3.14*(r*r);
    *per =2*3.14*r;
}

CodePudding user response:

The problem can be that you entered an incorrect sequence of symbols for a float number.

Write for example

if ( scanf("%f",&radius) == 1 )
{
    circle(radius, &area, &perimeter);
    printf("radius:%f area: %f, perimeter:%f ", radius, area, perimeter);
}
else
{
    puts( "Error: incorrect input." );
}

But in any case the function declaration

void circle(float, float *, float *);

does not correspond to the function definition

void circle(r, ar, per)
float r, *ar, *per;
{
    *ar =3.14*(r*r);
    *per =2*3.14*r;
}

Declare the function in the function definition like

void circle(float r, float *ar, float *per )
{
    *ar =3.14*(r*r);
    *per =2*3.14*r;
}

According to the C Standard (6.7.6.3 Function declarators (including prototypes)

6.7.6.3 Function declarators (including prototypes)

3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.

So you may not mix a function prototype with a function with an identifier list.

Pay attention to that according to the C Standard the function without parameters shall be declared like

int main( void )
  • Related