fscanf两行数据,执行计算,打印结果,fscanf接下来两行,在一个循环中?

时间:2017-04-03 02:29:06

标签: c arrays for-loop struct printf

我使用这个for循环从纬度和经度坐标文件中引入数据,然后将坐标转换为十进制度,度数转换为弧度,然后计算分离角度,并返回两个城市之间的距离。我需要比较文件中的前两行,计算距离,打印结果,然后执行接下来的两行。我完全按照我想要的方式得到它,但是有五个相同的for循环,每次只调整循环控制参数。有没有办法只用一个循环来完成这个?

   for(i=0;i<=ndata-9;i++)
   {     
       printf("\n%-15s     %3.0f %4.1f %c     %3.0f %4.1f %c",cities[i].location,
         cities[i].latdeg,cities[i].latmin,cities[i].directone,
         cities[i].longdeg,cities[i].longmin,cities[i].directtwo);
       fprintf(surface,"\n%-15s     %3.0f %4.1f %c     %3.0f %4.1f %c",
           cities[i].location,cities[i].latdeg,cities[i].latmin,
           cities[i].directone,cities[i].longdeg,cities[i].longmin,
           cities[i].directtwo);       
       if(cities[i-1].directone=='N')
       {
           polarone=(90.0-(cities[i-1].latdeg+(cities[i-1].latmin/60.0)))*(pi/180.0);
       }
       else
       {
           polarone=(90.0+(cities[i-1].latdeg+(cities[i-1].latmin/60.0)))*(pi/180.0);
       }
       if(cities[i].directone=='N')
       {
            polartwo=(90.0-(cities[i].latdeg+(cities[i].latmin/60.0)))*(pi/180.0);
       }
       else
       {
           polartwo=(90.0+(cities[i].latdeg+(cities[i].latmin/60.0)))*(pi/180.0);
       }
       if(cities[i-1].directtwo=='W')
       {
           azimuthone=(cities[i-1].longdeg+(cities[i-1].longmin/60.0))*(pi/180.0);
       }
       else
       {
           azimuthone=(360.0-(cities[i-1].longdeg+(cities[i-1].longmin/60.0)))*(pi/180.0);
       }
       if(cities[i].directtwo=='W')
       {   
           azimuthtwo=(cities[i].longdeg+(cities[i].longmin/60.0))*(pi/180.0);
       }
       else
       {
           azimuthtwo=(360.0-(cities[i].longdeg+(cities[i].longmin/60.0)))*(pi/180.0);
       }
       angle=acos(cos(polarone)*cos(polartwo)+sin(polarone)*sin(polartwo)*cos(azimuthtwo-azimuthone));
       distance=angle*radius;
   }
   printf("\nDistance between the two cities = %6.1f miles\n",distance); 
   fprintf(surface,"\nDistance between the two cities = %6.1f miles\n", distance);

1 个答案:

答案 0 :(得分:0)

DIVIDE AND CONQUER !!!

(以下是为了演示目的。我假设一切都是双倍的,城市有类型struct City。如果需要,请更改类型。另外,我没有调试它。)

const double deg_to_rad = pi/180, half_pi = pi/2, two_pi = pi*2;

inline double RadFromDeg(double degrees, double minutes) {
    return (degrees+minutes/60)*deg_to_rad;
}

// not sure if we really need inline here
inline void ObtainPolarAzimuth(double* polar, double* azimuth, struct City* city) {
    double temp = RadFromDeg(city->latdeg, city->latmin);
    if (city->directone == 'N')
        *polar = half_pi - temp;
    else
        *polar = half_pi + temp;
    // ... blablabla longdeg blablabla longmin blablabla *azimuth
}


// ... 

    ObtainPolarAzimuth(*polar1, *azimuth1, city[i-1]); 
    ObtainPolarAzimuth(*polar2, *azimuth2, city[i]);
    // ... blablabla angle blablabla cos blablabla sin

另外,imho最好写direct1direct2而不是directonedirecttwo