samedi 10 novembre 2018

Can't find the proper output in this code

I was asked to write a program about a traveling man. The direction of the program:


  1. Suppose a man (say, A) stands at (0, 0) and waits for the user to give him the direction and distance to go.

  2. The user may enter N E W S for north, east, west, south, and any value for the distance.

  3. 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;
    }
}
return 0;
}

But when I run the program after the first two inputs, it prints invalid outputs in the valid inputs.

output: enter image description here

Aucun commentaire:

Enregistrer un commentaire