470,632 Members | 1,457 Online

# C loop error search 1 Bit
Hello, I have data in a .csv describing a car journey.
The car starts at the position (0,0)-> (x,y). It moves only in 2 dimensions.
The .csv file contains two values separated by commas (,). The values include:
-The acceleration of the car in the direction it is currently pointing.
-The rotation of the car in which it is currently pointing.

The car always rotates at the beginning, then it accelerates for 1 second, stops
rotates again and accelerates again. and so on...

Now I have to calculate the maximum distance from the start position and the total distance covered.
However, I get in C when I run the script slightly different values than should finally come out.

Can someone take a look at my loop or algorithm? Do I have a mistake somewhere
how I calculate the covered distance?

Here is the code:

Expand|Select|Wrap|Line Numbers
1.     while ((token = strtok_r(save, "\n", &save)))
2.     {
3.         char* token1;
4.         char* save1 = token;
5.         double acceleration = atof(strtok_r(save1, ",", &save1));
6.         double rotation = atof(strtok_r(save1, ",", &save1));
7.
8.
9.         direction += rotation;
10.         double ax = acceleration * cos(direction);
11.         double ay = acceleration * sin(direction);
12.
13.         double vx = v0x + ax;
14.         double vy = v0y + ay;
15.
16.         double x = v0x + (ax/2) + x0;
17.         double y = v0y + (ay/2) + y0;
18.
19.
20.         fprintf(file, "%f,%f\n", x, y, direction);
21.
22.         double distance = sqrt(x*x + y*y);
23.         if(distance > max_distance) max_distance = distance;
24.         total_distance += sqrt((x-x0)*(x-x0) + (y-y0)*(y-y0));
25.
26.
27.         if(sqrt(vx*vx + vy*vy) > max_speed) max_speed = sqrt(vx*vx + vy*vy);
28.
29.         v0x = vx;
30.         v0y = vy;
31.         x0 = x;
32.         y0 = y;
33.     }
Feb 23 '21 #1
0 1649 