0

This is my code:

float pi = 3.1415;
float radius, area;

printf("Type the radius of you circle:");
scanf("%f,&radius");
fflush(stdin);

area=radius*radius*pi;

printf("The area of the circle with radius %f is:%f",radius, area);

return 0;

I have a float for PI, for the radius and for the area that will be calculated. The code will ask the user for the radius and then calculate the area.

The problem is: If the user type the radius as a integer, so for example "10" nothing works. I want the user to be able to type both integers and floats as the radius, so both "10" and "10.5" for example. How do I make that work? How can I storage a integer input as a float?

horsse
  • 107
  • 5
  • 7
    `scanf("%f,&radius");` I cannot believe that doesn't flag all sort of compiler warnings. Look at that carefully. `, &radius` shouldn't be *in* the format string. Unrelated, whatever resource told you to use `fflush(stdin);` paddle away from it from now on; that invokes *undefined behavior*. – WhozCraig Sep 05 '22 at 03:43
  • 1
    You have a typo: it should be `scanf("%f",&radius);` – kikon Sep 05 '22 at 03:43
  • 2
    Enable warnings and check your `scanf` parameters. – dimich Sep 05 '22 at 03:44
  • 1
    Thank you guys! The problem was the typo. I'm new to C and that helped a lot!! My college professor told me to use fflush(stdin) but now that you said that I'll look deeper into it, it's not the first time I see someone saying its bad. Thanks again! =) – horsse Sep 05 '22 at 04:01
  • And what happens when the user types "five"??? `radius` is uninitialised, and could/will give the floating point library heartburn... If you are going to ignore the return value from `scanf()`, at least initialise `float radius = 0.0, area;`.... – Fe2O3 Sep 05 '22 at 04:11
  • See [What is the use of fflush(stdin) in c programming?](https://stackoverflow.com/questions/18170410/what-is-the-use-of-fflushstdin-in-c-programming) – yano Sep 05 '22 at 04:29

1 Answers1

1

As the comments suggested, the problem was a typo:

scanf("%f,&radius"); should be scanf("%f",&radius);

Fixing the typo made the code work! Thank you so much for the people who commented!

horsse
  • 107
  • 5
  • _A_ problem was a typo. _The_ problem was compiling without all warnings enabled. Save time, enable them all and get rapid feedback like "warning: format '%f' expects a matching 'float *' argument [-Wformat=]". – chux - Reinstate Monica Sep 05 '22 at 13:58
  • How do I enable them? I tought they were enabled by default like in other langagues I've used in the past – horsse Sep 06 '22 at 05:40
  • 1
    To enable all warnings varies by compiler. I suggest searching for "enable all warnings" and your compiler name. – chux - Reinstate Monica Sep 06 '22 at 11:13