Problem in submitting my code to CodeWars due to decimal places

I am practicing C on code wars and there is this problem where i have to calculate the area of a regular n sides polygon inside a circle of radius r .

I have written the formula correctly but when i test , i am unable to submit my code.Here is my code:

#include <math.h>
#include <stdio.h>

double PI = 3.141592653589793; // Use this value as pi in your calculations if necessary

double area_of_polygon_inside_circle(double circle_radius, int number_sides) {
  double result,y;
  
  y = (double) number_sides;
  
  result = ((y/2)*circle_radius*circle_radius)*(sin(2*PI/y));
  
  result = (floor(1000.0*result)/1000);
  
  return result;
}

This is the error I am getting.

Expected: 502.526 Received: 502.525000 for area_of_polygon_inside_circle(13, 11)

>Solution :

In your code, you’re using the floor function to round the result to three decimal places. The use of floor to round the result truncates the value and might not handle all cases correctly, particularly when the value to be rounded is less than the midpoint between two integers. Instead of using floor, you could use the round function to round the result to the nearest integer before truncating it to three decimal places.

Try this please:

#include <math.h>
#include <stdio.h>

double PI = 3.141592653589793;

double area_of_polygon_inside_circle(double circle_radius, int number_sides) {
  double result, y;
  
  y = (double) number_sides;
  
  result = ((y / 2) * circle_radius * circle_radius) * (sin(2 * PI / y));
  
  result = round(result * 1000) / 1000; // Round to three decimal places
  
  return result;
}

int main() {
  printf("%.3lf\n", area_of_polygon_inside_circle(13, 11));
  return 0;
}

Leave a Reply