0

I have a piece of code in C, which is supposed to compute the circumference. No matter what I put in for variable Z when asked for it, it always prints 0.000000

Any ideas?

#include <stdio.h>
int main()
{
    double pi = 3.1415926;
    double z = 0.0;
    printf("What is the radius of the circle? \n ");
    scanf("%1f", &z);
    double c =  2.0 * pi * z;
    printf("The circumference is %1f", c);
    return 0;
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631

3 Answers3

2

Change %1f to %lf.

Like so:

#include <stdio.h>
int main()
{
    double pi = 3.1415926;
    double z = 0.0;
    printf("What is the radius of the circle? \n ");
    scanf("%lf", &z);
    double c =  2.0 * pi * z;
    printf("The circumference is %lf", c);
    return 0;
}
Sam
  • 608
  • 4
  • 11
0

For reading into z, a double, you have to use scanf("%lf", &z) instead of "%1f".

tif
  • 1,424
  • 10
  • 14
0

You were very close. try this

#include <stdio.h>
int main()
{
    double pi = 3.1415926;
    double z = 0.0;
    printf("What is the radius of the circle? \n ");
    scanf("%1f", &z);
    double c =  2.0 * pi * z;
    printf("The circumference is %.1f", c);
    return 0;
} 

your logic is telling the float that it needs a whole number, but no decimals afterwards

  • 1
    The `%f` specifier is used for `float`s, `double`s need the `%lf` specifier (with a lowercase L). The code provided in your answer doesn't produce the 'correct' answer and may invoke undefined behavior. [Try it online](https://tio.run/##VY7LDoIwFET3fMUEgxGiDSiYGF8/YeLGDV6KNIHS9LHB@O1YHwu9u7mTOTOk1OJGNI4TIal1FcfO2Er0rDkEQlp0pZCzOLgH8Ff17tpyKIE9VizLs2KzXG9/rcE7KUs/P6U9oZ6F56a0EAa24dBlJZxBX78VCU0tP@IiEcafkKFS@kyU1eEc0yH@w5PHY8lSJK8RCYb/otMX6bqaay6Jv1oj9kbRl6S5dVrCT3xgHHNWPAE "C++ (gcc) – Try It Online") – pizzapants184 Aug 30 '18 at 21:31