Clan x86

Technical (Development, Security, etc.) => General Programming => Topic started by: wires on June 14, 2006, 05:27:09 pm

Title: [C] Calculate area/circumference of circle
Post by: wires on June 14, 2006, 05:27:09 pm
Code: [Select]
#include <stdio.h>

int main() {
float radius;
int valid;
const float Pi = 3.14159;

do {
printf("Input the radius of a circle: ");

valid = scanf("%f", &radius);

while (getchar() != '\n');

if (valid == 0) {
printf("\nInvalid input.  Try again.\n\n");
} else if (valid == 1) {
if (radius == 0) {
printf("\nNo circle can have a radius of 0.  Try again.\n\n");
} else if (radius < 0) {
printf("\nNo circle can have a negative radius.  Try again.\n\n");
}
}
} while (radius == 0 || valid == 0);

printf("\nThe circumference is %f", Pi * 2 * radius);
printf("\nThe area is %f\n", Pi * radius * radius);

return 1;
}
Criticise plz.
Title: Re: [C] Calculate area/circumference of circle
Post by: iago on June 14, 2006, 05:33:10 pm
One small thing that is barely worth mentioning is the way you do an empty while loop.  You did:
while(...);

I find that confusing to see.  I prefer doing:

while(...)
    ;

But that's a personal thing. 
Title: Re: [C] Calculate area/circumference of circle
Post by: d&q on June 14, 2006, 05:42:53 pm
Added some minor stuff. And fixed the while loop (It would calculate a negative number regardless.)

Code: [Select]
#include <stdio.h>

int main() {
float radius;
int valid;
const float Pi = 3.14159;
char repeat, option;

printf("Hey all you goofy goobers! Do you want to do some MATH!? [Y/N] ");
scanf("%c", &option);
    if (option == 'N' || option == 'n') {
   printf("Well, then you suck WiRes!");
    } else {
for( ; ;)
{
   do {
   printf("\nInput the radius of a circle: ");

   valid = scanf("%f", &radius);

   while (getchar() != '\n');

   if (valid == 0) {
   printf("\nInvalid input.  Try again.\n");
     } else if (valid == 1) {
   if (radius == 0) {
   printf("\nNo circle can have a radius of 0.  Try again.\n");
   } else if (radius < 0) {
   printf("\nNo circle can have a negative radius.  Try again.\n");
           }
        }
      } while (radius <= 0 || valid <= 0);
printf("\nThe circumference is %f", Pi * 2 * radius);
printf("\nThe area is %f\n", Pi * radius * radius);
printf("\nDo you want to recalculate? [Y/N]");
scanf("%c", &repeat);

    if (repeat == 'N' || repeat == 'n')
   break;
    }
}         
return 1;
}