-
Decimal question
Hi I just started learning c yesterday and I wrote this simple c program to find the area of a circle when you input the radius.
Code:
#include <stdio.h>
#include <stdlib.h>
int radius, area;
int main()
{
printf( "Enter radius (i.e. 10): " );
scanf( "%d", &radius );
area = (int) (3.14159 * radius * radius);
printf( "\n\nArea = %d\n", area );
system("PAUSE");
return 0;
}
The problem is that it displays the radius as a whole number rounded down. Is there a way to make it display decimals, or better yet is there a way to make it round up or down depending upon the number? ex. 19.4=19, 19.5=20.
-
Your area variable is an int. Make it a float or double if you want decimals. Get rid of the int typecast in your calculation too. You'll have to change printf() to use %f instead of %d as well.
-
For rounding Ints (ints round down always) add .5 before you cast the answer as an int.
-
integers have no decimal.
It also doesn't exactly round down. It does something called truncate the variable. Also, global variables (variables outside of main) can get tricky especially if you don't need them (it's hard to keep track) You can do this
Code:
#include <stdio.h>
int main(void){
int radius;
float area;
printf( "Enter radius (i.e. 10): " );
fflush(stdout); /*need to make sure this is actually displayed*/
scanf( "%d", &radius ); /*remember this is only integers*/
area = (3.14159 * radius * radius);
printf( "\n\nArea = %.2f\n", area );
system("PAUSE");
return 0;
}
If you user inputs a float for radius ex: 2.3 it will truncate it to 2 because it is an integer. the %.2f only displays 2 places after the decimal.
-
Cool! It displays decimals now. Thanks a lot!