Home > Enterprise >  Getting incorrect answer in C
Getting incorrect answer in C

Time:11-24

I am a beginner and wrote this code to calculate area of circle but it gives an incorrect answer. If I put radius = 7, then area should be 22/7*7*7 = 22*7 = 154 but I get 147.00. Why is that so?

#include<stdio.h>
#include<conio.h>

float aoc (float radius);

int main()
{
    float answer, radius;
    printf("Enter value of radius");
    scanf("%f",&radius);
    answer=aoc(radius);
    printf("area of circle is %f",answer);
    getch();    
}

float aoc (float radius)
{
    float area = 22*radius*(1/7*radius);
    return(area);   
}

CodePudding user response:

float(1/7) = 0, You can do -

float area = 22*radius*(1.0/7.0*radius);

Or this-

#include<stdio.h>
#include<conio.h>

float aoc (float radius);

int main()
{
    float answer, radius;
    printf("Enter value of radius");
    scanf("%f",&radius);
    answer=aoc(radius);
    printf("area of circle is %f",answer);
    getch();
    
}

float aoc (float radius)
{
    float area = (22*radius*radius)/7;
    return(area);   
}

CodePudding user response:

You don't need to use 22/7. Just declare a global variable pi=3.14.

Here's your code:

#include<stdio.h>
#include<conio.h>

float PI=3.14;

float aoc (float radius);

int main()
{
    float answer, radius;
    printf("Enter value of radius");
    scanf("%f",&radius);
    answer=aoc(radius);
    printf("area of circle is %f",answer);
    return 0;
    
}

float aoc (float radius)
{
    float area = PI*radius*radius;
    return(area);   
}
  •  Tags:  
  • c
  • Related