Search code examples
cprintfdoublefunction-prototypes

printing doubles from a function outside of main


I am new to c and trying to use a function outside of the main function, I wanted to test what I was getting but found an error when I print the value from the function.

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

/*function prototype f*/
int f(double x);

/*main*/
int main(void){

   double x = 0.1;

   printf("the value is %.3f\n", f(x)); 
   printf("the value is %.3f", sqrt(1.0-(x*x))); 

   return 0;
}

int f(double x){
    double value;
    value = sqrt(1.0-(x*x));}
    return value;
}

This basic code finds a value from a given x that I want to later use in a loop. when I run this however I get the following output

the value is -1.....
the value is 0.995

(… is a random sequence of characters)

I am not sure what the difference is in the function f and the actual value calculated inside the main function and why I am getting this issue


Solution

  • You were using int instead of double for your prototype. This should give you the right answer.

    #include <stdio.h>
    #include <math.h>
    #include <conio.h>
    
    /*function prototype f*/
    double f(double x);
    
    /*main*/
    int main() {
    
        double x = 0.1;
    
        printf("the value is %.3f\n", f(x));
        printf("the value is %.3f", sqrt(1.0 - (x*x)));
    
        _getch();
        return 0;
    }
    
    double f(double x) {
        double value;
        value = sqrt(1.0 - (x*x));
        return value;
    }