ani ben
ani ben

Reputation: 145

Output is Mistakenly Zero in c program

I am learning C I decided to make a file that would calculate the surface area and volume of a sphere once its radius was given by the user. However, when I tried compiling the program by typing in:

gcc Sphere.c -lm -o Sphere

and I enter the radius when I am prompted to, the SA and V output is always zero. What's going on here? I may be overlooking something simple. Here is my code:

#include <stdio.h>
#include <math.h>

double main()
{
    double rad;
    double sa, vol;
    const double pi = 3.141592654;

    printf("enter the radius of the sphere: \n");
    scanf("%f", &rad);

    vol = (4.0/3.0)* pi *(pow(rad,3));
    sa = 4.0 * pi * (pow(rad,3));

    printf("Volume of sphere is: %.3f", vol);
    printf("\n Surface area of sphere is: %.3f", sa);

    return 0;

}

Upvotes: 0

Views: 220

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You are using the wrong scanf() specifier.

The correct specifier for double is "%lf", and scanf() returns a value which you are ignoring causing possibly undefined behavior.

Also, main() does not have the signature you used, it returns a int, not a double or anything else, so your code would work if you fix at as follows

#include <stdio.h>
#include <math.h>

int main(void)
{
    double rad;
    double sa, vol;
    const double pi = 3.141592654;

    printf("enter the radius of the sphere: \n");
    if (scanf("%lf", &rad) == 1)
    {
        vol = (4.0/3.0)* pi *(pow(rad,3));
        sa = 4.0 * pi * (pow(rad,3));

        printf("Volume of sphere is: %.3f", vol);
        printf("\n Surface area of sphere is: %.3f", sa);
    }
    else
        fprintf(stderr, "Invalid Input\n");

    return 0;

}

Also, vim is a text editor, gcc is a compiler, and you are invoking the compiler with the least diagnostic that is possible, I recommend

gcc -Wall -Werror -g3 -O0 Sphere.c -o Sphere -lm

which will let you know about silly mistakes that you might somtimes make.

Edit:

As noticed by @A.S.H in the comments below, there is a mistake with the surface area formula it has to be

A = 4πr2

you have

A = 4πr3

which is wrong.

Upvotes: 2

Related Questions