Re: a problem about "sqrt"
On Nov 1, 2:23 am, linlinfan...@163.com wrote:
why it print wrong result? I can't find the wrong place.
#include<stdio.h>
#include<math.h>
double distance(double a ,double b,double c,double d);
int main()
{
double x1,y1,x2,y2;
double result;
printf("Enter four numbers:");
scanf("%f%f%f%f",&x1,&y1,&x2,&y2);
result=distance(x1,y1,x2,y2);
printf("The distancd is %.1f",result);
return 0;
}
double distance(double a,double b,double c,double d)
{
return sqrt((a-c)*(a-c)+(b-d)*(b-d));
}
The reason why it prints the wrong result is that you're using
scanf. Try doing it the C++ way:
#include <iostream>
#include <cstddef>
#include <cmath>
extern double distance( double a, double b, double c, double d ) ;
int
main()
{
std::cout << "Please enter four numbers: " ;
double x1 ;
double y1 ;
double x2 ;
double y2 ;
if ( std::cin >> x1 >> y1 >> x2 >> y2 ) {
std::cout << "The distance is: "
<< distance( x1, y1, x2, y2 )
<< std::endl ;
} else {
std::cerr << "Those weren't four legal numbers"
<< std::endl ;
}
return EXIT_SUCCESS ;
}
double
distance(
double x1,
double y1,
double x2,
double y2 )
{
return std::sqrt( ((x1-x2) * (x1-x2)) + ((y1-y2)*(y1-y2)) ) ;
}
You should just forget about stdio.h (except for a few things
like remove or rename); the interface is horribly broken, and
extremely error prone and unnatural. (The iostream interface
isn't without problems either, but it's still an order of
magnitude better than stdio.h.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34