I was asked to write a program about a traveling man. The direction of the program:
Suppose a man (say, A) stands at (0, 0) and waits for the user to give him the direction and distance to go.
The user may enter N E W S for north, east, west, south, and any value for the distance.
When the user enters 0 as direction, stop and print out the location where the man stopped
My Code:
#include <stdio.h>
int main() {
float x=0,y=0;
char dir;
float mile;
while(1){
printf("Enter input direction as N,S,E,W (0 to exit): ");
scanf("%c",&dir);
if(dir == '0')
break;
if(dir != 'N' && dir != 'S' && dir != 'E' && dir != 'W'){
printf("Invalid Direction, re-enter \n");
continue;
}
printf("Input mile in %c dir: ",dir);
scanf("%f",&mile);
if(dir == 'N'){
y+=mile;
}
else if(dir == 'S'){
y-=mile;
}
else if(dir == 'E'){
x+=mile;
}
else if(dir == 'W'){
x-=mile;
}
}
printf("\nCurrent position of A: (%4.2f,%4.2f)\n",x,y);
return 0;
}
But when I run the program after the first two inputs, it prints invalid outputs in the valid inputs.