Array changes values somehow?
I'm working on a HW problem, and for the life of me, i can't figure out why the array I'm using is changing the values of its variables.
I put a lot of double checking to figure out when it's happening in the code, but I don't WHY it's happening. Can anyone shed some light on this?
Code:
#include <stdio.h>
int main()
{
double x[4];
char OP[4];
double y[4];
double answer;
int operation;
printf("x: ");
scanf("%lf %lf %lf %lf %lf", &x[0], &x[1], &x[2], &x[3], &x[4]);
while (getchar() != '\n');
printf("2xCHECK: You entered: %.2lf %.2lf %.2lf %.2lf %.2lf\n", x[0], x[1], x[2], x[3], x[4]);
printf("OP: ");
scanf("%c %c %c %c %c", &OP[0], &OP[1], &OP[2], &OP[3], &OP[4]);
while (getchar() != '\n');
printf("2xCHECK: You entered: %c %c %c %c %c\n", OP[0], OP[1], OP[2], OP[3], OP[4]);
printf("y: ");
scanf("%lf %lf %lf %lf %lf", &y[0], &y[1], &y[2], &y[3], &y[4]);
while (getchar() != '\n');
printf("2xCHECK: You entered: %.2lf %.2lf %.2lf %.2lf %.2lf\n", y[0], y[1], y[2], y[3], y[4]);
printf("\n\nONCEMORE: You entered: %.2lf %.2lf %.2lf %.2lf %.2lf\n", x[0], x[1], x[2], x[3], x[4]);
//problem happens here. WHY??
for(int k=0;k<5;k++)
{
if(OP[k]=='+')
{
operation = 1;
}
else if (OP[k]=='-')
{
operation = 2;
}
else if (OP[k] =='*')
{
operation = 3;
}
else if (OP[k] =='/')
{
operation = 4;
}
else
{
operation = 0;
}
printf("%.2lf %c %.2lf = ", x[k], OP[k], y[k]);
switch(operation)
{
case 1:
answer = x[k] + y[k];
break;
case 2:
answer = x[k] - y[k];
break;
case 3:
answer = x[k] * y[k];
break;
case 4:
answer = x[k] / y[k];
break;
default:
break;
}
printf("%.2lf\n", answer);
}
return 0;
}
The program is supposed to take the first element of X and use the supplied operation, for the purpose of the example...an asterisk for multiplication, and multiply it against the 1st element of Y. It goes on to the second element...etc...
Here's is what I'm putting into the program:
x: 1.8 2.4 3 4.9 5.5
OP: - * + - /
y: 1.5 2 3.66 4.1 5
And here is my exact output:
Code:
x: 1.8 2.4 3 4.9 5.5
2xCHECK: You entered: 1.80 2.40 3.00 4.90 5.50
OP: - * + - /
2xCHECK: You entered: - * + - /
y: 1.5 2 3.66 4.1 5
2xCHECK: You entered: 1.50 2.00 3.66 4.10 5.00
ONCEMORE: You entered: 5.00 2.40 3.00 4.90 0.00
5.00 - 1.50 = 3.50
2.40 * 2.00 = 6.80
3.00 + 3.66 = 6.66
4.90 - 4.1 = 0.08
0.00 / 5.00 = 0.00
So as you can see, the array of X's, for whatever reason, changes it's [0] and [4] elements for NO REASON right before the for loop. It's very frustrating.
Why is this, and how can I fix it?