Rotating matrix of points for a custom angle

85 views Asked by At

I wanted to make matrix of points and rotate them for a custom angle.
I get a bunch of 0's when I enter the desired angle, can't figure out why.
Might be a pretty simple mistake, I'm kind of new to programming in C, trying to learn.

Here's my code:

#define _CRT_SECURE_NO_WARNINGS

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

int main(){
double pi = 3.14159265;
double rot[2][2], obj[2][10], obj2[2][10];
int a, c, d, i, j;
double x,y, sum=0;
double element = 0;

printf("Enter the number of columns of the matrix:\n");
scanf("%d", &a);

printf("Enter the elements of the matrix:\n");

for (c = 0; c < 2; c++){
    for (d = 0; d < a; d++){
        scanf("%lf", &obj[c][d]);
    }
}

printf("Enter the desired clockwise rotation angle:\n");
scanf("%lf", &x);
if ((int)x > 360){
    x = (int)x % 360;
}
if ((int)x < 0){
    x = 360 + x;
}

y = (pi / 180) * x;

rot[0][0] = cos(y);
rot[0][1] = sin(y);
rot[1][0] = -sin(y);
rot[1][1] = cos(y);


for (c = 0; c < 2; c++){
    for (d = 0; d < a; d++){
        for (i = 0; i < 2; i++){
            sum += rot[c][i] * obj[i][d];
        }
        obj2[c][d] = sum;
        sum = 0;
    }
}

printf("Rotated object in matrix form:\n");
for (c = 0; c < 2; c++){
    for (d = 0; d < a; d++){
        printf("%f\t", obj2[c][d]);
    }
    printf("\n");
}

system("PAUSE");
return 0;
}  

Had a problem with accepting values into matrix fields, pretty much all values were messy. Also there was & in the printf function so it printed the wrong thing. All solved now, tweaked some outputs to look better but it's a functioning code now.

EDIT: After fixing the printf, I get http://prntscr.com/7fgq7m after the debug.
EDIT2: Entering values works properly, will now play with sin() and cos() part to see if that works aswell.

FINAL EDIT: Everything works smoothly for the values I planned, will do a lot more testing with friends, but this looks fine.
Thank you everyone that helped, much appreciated.

2

There are 2 answers

3
Hsyn On BEST ANSWER
scanf("%.lf", &obj[c][d]);

it is wrong. "%.lf" there is no such a specifier. It must be "%lf" for double type values.

Also you are using fflush(stdin); which is not right to flush standart input buffer and it is undefined behaviour according to standarts (C11 7.21.5.2). (okey compilers supports it, but wrong).

You can use your own function something like that;

void FlushStdin(void)
{
     int ch;    
     while((ch = getchar()) != '\n' && ch != EOF )
          ;
}
12
Weather Vane On

Remove the . from this line so it reads

scanf("%lf", &x);

which error would be revealed if you printed the input value.

Also, I see you are fumbling with checking the input value but sin() and cos() only fail with stupidly extreme inputs.

Another point, fflush(stdin) is implementation defined and isn't usually necessary.

UPDATE here is a bug

for (d = 0; d < a; c++)

which should be

for (d = 0; d < a; d++)