首页 > 解决方案 > 使用结构从另一个函数调用变量

问题描述

我是 C 新手,我刚刚了解了struct. 我要制作一个从文件中读取数据并打印出来的程序。

我的子任务之一是计算 2 点之间的距离。我正在使用距离函数所见的半正弦公式。

然而,我的问题是我试图从函数中获取fst->Lat和获取,但它不起作用。我已经突出显示了它们所在的行,以使其清楚。fst->Longstage_1_read

我如何获得这些值?它们是文件中读取的第二个和第三个值,但是使用我当前的代码,看起来它正在读取第一个和第二个值。我已经尝试了一段时间,但无法获得我需要的值。

struct file_data{
    char User[5];
    char Long[12];
    char Lat[12];
    char Date[11];
    char Time[3];
};

double stage_1_read(void);
double distance(struct file_data fst);
double toRadian(double x);

int main(){
    printf("%f", stage_1_read());
    return 0;
}

double stage_1_read(void){
    /* This function takes the data from the input file,reading and printing 
    the User ID, Location (longitude and latitude), Date, Time, and Distance*/
    double d;
    char line[256];
    struct file_data fst;

    if (fgets(line, 256, stdin) != NULL) {
        sscanf(line, "%s %s %s %s %s", fst.User, fst.Long, fst.Lat,
        fst.Date, fst.Time);
    }
    else{
        printf("Failed to read file. Check file and try again.");
        exit(EXIT_FAILURE);
    }
    d = distance(fst);
    printf("Stage 1\n==========\n");
    printf("User: #%s\n", fst.User);
    printf("Location: <%s %s>\n", fst.Long, fst.Lat);
    printf("Date: %s\n", fst.Date);
    printf("Time: %s\n", fst.Time);
    printf("Distance to reference: %.2f", d);
    return 0;
}

double distance(struct file_data fst) {
    /* This function is designed to calculate the distance between the check-in 
    POI and the reference point provided*/
    double angle_distance, chord_length, dist;
    double lat_2, long_2;

    lat_2 = *fst.Lat;
    long_2 = *fst.Long;

    double var_lat = toRadian(lat_2 - LAT_1);
    double var_long = toRadian(long_2 - LONG_1);

    chord_length = pow(sin(var_lat/2),2) + cos(toRadian(LAT_1)) * 
    cos(toRadian(lat_2)) * pow(sin(var_long/2),2);

    angle_distance = 2 * atan2(sqrt(chord_length), sqrt(1 - chord_length));

    dist = 6371 * angle_distance;

    return dist;
}

double toRadian(double x) {
    x = PI/DEGREES;
    return x;
}  

更新:

根据要求更改了一些代码。

标签: cstruct

解决方案


您正在尝试引用在不同函数中声明的变量(尽管我不确定如何在不分配内存的情况下声明指向结构的指针对您有用),但是您可以将其声明为没有and thenstruct file_data *fst的局部变量*您可以将其称为fst.Lat。如果您坚持将其用作指针,则应为此分配内存,您可以使用malloc或任何其他适合您的内存分配方法。

但是对于我们的业务,当您fstdistance函数中引用变量时,您正在引用fst您刚刚在该函数中声明的新变量。

如果您想从两个函数(或任何函数)引用相同的变量,一个选项是使该变量成为全局变量(在函数范围之外声明它),或者您可以distance接受指向该结构的指针作为参数

double distance(double d, struct file_data *fst)

然后您将能够访问您在stage_1功能下创建的那个


推荐阅读