问题
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
回答1:
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
.
回答2:
Try this :
scanf("%lf",&a);
or change the variable a to float:
float a;
回答3:
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.)
来源:https://stackoverflow.com/questions/9051733/turbo-c-compiler-issue-sqrt-function-not-working-with-variable-arguments