Question

I searched the question similar to my problem Similar problem. But my problem is when using Turbo C compiler v3.0. Should I have to do some additional work for math.h file? please help.

int main (void){
    double result, a;
    clrscr();
    printf("Enter a # for square root.\n");
    scanf("%f",&a);
    printf("a = %f\n",a);
    result = sqrt(a);
    printf("a = %f  and square root is %f\n",a, result);
    getch();
    return 0;
    }

The Output is like this:

Enter a # for square root.

64

a = 0.000000

a = 0.000000 and square root is 0.000000

Was it helpful?

Solution

For scanf(), %f is for float. You need to use %lf for double:

printf("Enter a # for square root.\n");
scanf("%lf",&a);

This is in contrast to printf() where type-promotion allows %f to be used for both float and double.

OTHER TIPS

Try this :

   scanf("%lf",&a);

or change the variable a to float:

 float a;

In addition to using "%lf" as the scanf format, you need to have

#include <stdio.h>
#include <math.h>
#include <conio.h> /* I think */

The last one is for the clrscr() and getch() calls; they're non-standard, but I think they're declared in <conio.h>.

Without the #include <math.h>, the compiler is going to assume that sqrt() returns an int result rather than double.

(An aside: Why do you call clrscr()? What is the benefit of clearing the screen before doing anything else? The getch() call isn't strictly necessary either, but on some systems the default method of running a program results in the window being closed as soon as it terminates.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top