C语言初学结构体,不太懂错哪了

P5735 【深基7.例1】距离函数

Loving_coding @ 2023-01-13 02:39:35

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

int main(){
int i,j;
float dis1=0,dis2=0,dis=0;
    struct point{
        int  x, y;
    };
    point p[3] = 
    { 
    {scanf("%f%f",&p[0].x,&p[0].y)},
    {scanf("%f%f",&p[1].x,&p[1].y)},
    {scanf("%f%f",&p[2].x,&p[2].y)} 
    };
    for (i = 0; i <= 1; i++) {
        dis1 =dis1+ sqrt(pow(p[i].x-p[i + 1].x, 2)+ pow(p[i].y - p[i + 1].y, 2));
    }
    for (j = 0; j < 1; j++) {
        dis2  = sqrt(pow(p[j].x - p[j + 2].x, 2) + pow(p[j].y - p[j + 2].y, 2));
    }

    dis = dis1 + dis2;
    printf("%f", &dis);
    return 0;
}

by MicroSun @ 2023-01-13 08:06:12

@PCwqyy 过不了的


by PCwqyy @ 2023-01-13 08:12:09

@MicroSun 好久没做红题了……


by PCwqyy @ 2023-01-13 08:15:50

坐标值是实数


by MicroSun @ 2023-01-13 08:16:55

OK,lz我调完了,AC代码见下

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

using namespace std;
int main(){
int i,j;
double dis1,dis2,dis3,dis;
    struct point{
        double  x, y;
    }p[3];
    scanf("%lf%lf",&p[0].x,&p[0].y);
    scanf("%lf%lf",&p[1].x,&p[1].y);
    scanf("%lf%lf",&p[2].x,&p[2].y);
    dis1 =sqrt(pow(p[0].x-p[1].x, 2)+ pow(p[0].y - p[1].y, 2));
    dis2 =sqrt(pow(p[1].x-p[2].x, 2) + pow(p[1].y - p[2].y, 2));
    dis3 =sqrt(pow(p[2].x-p[0].x,2)+pow(p[0].y-p[2].y,2));
    dis = dis1 + dis2+dis3;
    printf("%.2lf", dis);
    return 0;
}

by MicroSun @ 2023-01-13 08:18:04

@Loving_coding 你仔细看看和你的代码有啥不一样(我是尽量按照你的源代码改的)


by PCwqyy @ 2023-01-13 08:18:58

献出我一年前的代码

 #include <bits/stdc++.h>
using namespace std;
double dis(double X1,double Y1,double X2,double Y2)
{
    return sqrt(pow(X2-X1,2)+pow(Y2-Y1,2));
}
int main()
{
    double x1,x2,x3,y1,y2,y3,sum=0;
    cin>>x1>>y1>>x2>>y2>>x3>>y3;
    sum=dis(x1,y1,x2,y2)+dis(x1,y1,x3,y3)+dis(x3,y3,x2,y2);
    printf("%.2f",sum);
    return 0;
}

by Loving_coding @ 2023-01-13 13:14:44

@MicroSun 谢谢兄弟啊,已经关注你了。看来还是我对C的语法掌握不够好,想问个问题,为什么dis和x,y要用double而不是float定义呢?


by Loving_coding @ 2023-01-13 13:15:10

@PCwqyy 谢谢兄弟,关注你了


by MicroSun @ 2023-01-13 13:19:31

@Loving_coding 额,我一般习惯用double,因为除非在空间不足的情况下,用double可以提高精度。


by Loving_coding @ 2023-01-13 13:30:10

@MicroSun 噢噢好的


上一页 |