#include<stdio.h>
int a, b, h, area, perimeter;
float pi;
void rectangle() {
printf("enter rectangular base length");
scanf("%d", &a);
printf("enter rectangular base height\n");
scanf("%d", &b);
area = a * b;
perimeter = (a b) * 2;
printf("area of a rectangle = %d\n", area);
printf("perimeter of a rectangle = %d", perimeter);
}
void circle() {
pi = 3.14;
printf("enter the length of the circle radius\n");
scanf("%d", &a);
area = pi * a * a;
perimeter = 2 * pi * a;
printf("area of the circle = %d\n", area); //I want this part to conversion from int to float
printf("perimeter of the circle = %d", perimeter);
}
int main() {
printf("Choose which way you will operate\n");
printf("circle=1\nrectangle=2\n");
scanf("%d", &h);
switch (h) {
case 1:
printf("you chose a circle\n");
circle();
break;
case 2:
printf("you chose a rectangle\n");
rectangle();
break;
}
}
As I wrote in the code, I want the part I specified to be converted from int to float. How can i do it? I was know like that but it didn't work -> (float)area = a * b;
CodePudding user response:
You would probably want to define PI as a constant. Prefer to minimize scope of variables (now local to the function that needs them). Use floating point types (float, double etc) when needed to store fractional values with more than integer precision. Make sure you use the %f
to print them (optionally, specify how many digits you want to see here %.1f means 1 fractional digit):
#define PI 3.14
void circle() {
printf("enter the length of the circle radius\n");
float a;
scanf("%f", &a);
float area = PI * a * a;
float perimeter = 2 * pi * a;
printf("area of the circle = %.1f\n", area);
printf("perimeter of the circle = %.1f", perimeter);
}
CodePudding user response:
I found that your code here:
area = pi * a * a;
where "pi" you defined it as a float constant, so compiler will warn at this line something like "assign float to a integer", you should know that no matter how many integers in a formula, even one float number in it, the type of final value will be automatically converted to float So you should declare area as:
float area; // or double area
By your comment in this line:
printf("area of the circle = %d\n", area); //I want this part to conversion from int to float
I guess you want to print a number with decimal part.
You can try this:
printf("area of the circle = %.3f\n", area);
".3" after "%" means print 3 decimal digits, or to say the precision is 3; "f" after ".3" means print argument 1 as a float number.