简体   繁体   English

C 中的 sqrt 函数不返回精确值

[英]sqrt function in C not returning exact value

My code is as follows:我的代码如下:

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

int distance(int x1, int y1, int x2, int y2){
    double value = sqrt(pow((double)(x2- x1),2.0) + pow((double)(y2 - y1),2.0));
    return value;
}
int main(void){
    int A_x, A_y, B_x, B_y, C_x, C_y;
    printf("Enter 1st point:");
    scanf("%d", &A_x);
    scanf("%d", &A_y);
    printf("Enter 2nd point:");
    scanf("%d", &B_x);
    scanf("%d", &B_y);
    printf("Enter 3rd point:");
    scanf("%d", &C_x);
    scanf("%d", &C_y);
    double AB = distance(A_x, A_y, B_x, B_y);
    printf("%.2lf", AB);
    // double powered = pow((double)(A_x- B_x),2.0) + pow((double)(A_y - B_y),2.0);
    // double squared = sqrt(powered);
    // printf("%.2lf", squared);
    double BC = distance(B_x, B_y, C_x, C_y);
    printf("%.2lf", BC);
    double CA = distance(C_x, C_y, A_x, A_y);
    printf("%.2lf", CA);
    if(AB+BC>CA && AB+CA>BC && BC+CA>AB){
        double perimeter = AB+BC+CA;
        printf("Perimeter of triangle = %.2lf",perimeter);
        return 0;
    }else{
        printf("Invalid traingle");
        return -1;
    }
    
}

I am getting the following in the compiler:我在编译器中得到以下内容:

在此处输入图片说明

I am not exactly sure why I'm getting 2.00 for AB instead of 2.83.我不确定为什么我得到 AB 的 2.00 而不是 2.83。 Would be glad if someone could explain where I went wrong :)如果有人能解释我哪里出错了,我会很高兴:)

The function distance returns an integer, therefore it truncates the result of the sqrt.函数 distance 返回一个整数,因此它会截断 sqrt 的结果。 You should change the declaration of:您应该更改以下声明:

 int distance(int x1, int y1, int x2, int y2)

to

double distance(int x1, int y1, int x2, int y2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM