Function does not respond correctly

Asked

Viewed 54 times

1

Trying to calculate the volume of the sphere returns a strange number like -1.#QNAN0.

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

float pi = 3.14;
float param(int x){
float vol,y;
y = pow(x,3);
vol = (4*y)/3*pi;
return vol;
}
int main(){
int x, y;
printf("Digite o raio de uma esfera: ");
scanf(" %f", &x);
y = param(x);
printf("\nO volume de uma esfera eh %f \n", y);
system("pause");
return 0;
}
  • 1

    The result and radius is set to integer int. Save variables as float, ideal for working with broken numbers: float x, y;

1 answer

1


I couldn’t even compile this code because I use a modern compiler configured to give more quality to the code. When I change to compile there is no error, it was like this:

#include <stdio.h>
#include <math.h>
#ifndef M_PI
#    define M_PI 3.14159265358979323846
#endif
float param(float x) {
    return (4 * pow(x, 3)) / 3 * M_PI;
}
int main() {
    float x;
    printf("Digite o raio de uma esfera: ");
    scanf(" %f", &x);
    printf("\nO volume de uma esfera eh %f \n", param(x));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Perhaps the biggest problem is to declare the variable as integer and try to take as decimal value, you have to choose which to use and keep synchronized. The rest was just simplification and standardization of the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.