简体   繁体   中英

c program that calculate the area of the circle

#include<stdio.h>

int main() {
   float radius, area;

   printf("\nEnter the radius of Circle : ");
   scanf("%d", &radius);

   area = 3.14 * radius * radius;
   printf("\nArea of Circle : %f", area);

   return (0);
}

I've written the above program to work out the area of a circle given its radius but I'm getting very strange values and I cannot figure out why.

The problem is that you're using an integer format specifier %d to scan into a float point variable radius . This is actually undefined behaviour (a) , and you should be using %f to scan in float variables.

The standard is explicit that this is a requirement (quote below extracted from C11 7.21.6.2 The fscanf function /12 , and C++ defers to the C standard for legacy stuff like this):

a,e,f,g - Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.


Of course, if this is a C++ question, you would be better off using the facilities from iostream rather than stdio/cstdio . The type safety of C++ will generally avoid this issue since behaviour adapts to the types rather than you having to manually specify things.

That could be as simple as something like:

float radius;
std::cout << "\nEnter the radius of Circle : ";
std::cin >> radius;

(a) One of the things that might happen is that scanf happily places the integer into the memory where the floating point value exists. Unfortunately, they tend to use different encoding schemes (such as two's complement against single precision IEEE754) so will end up with the exact symptoms you describe.

Of course, being undefined behaviour, one of the other things that might happen is to total breakdown of causality, followed by complete destruction of the universe :-)

And, yes, that's hyperbole, but it's meant to stress how bad it is to rely on undefined behaviour. Obviously the consequences won't really be that bad, but it's often a good idea to assume they will be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM