C Slope finder returning weird numbers -
in c, attempting create program finds slope in effort learn more language. have created 6 variables hold needed information:
//variables int one_x; int one_y; int two_x; int two_y; float top_number; float bottom_number;
then, created way user enter information.
printf("------------------\n"); printf("enter first x coordinate.\n"); printf(">>> \n"); scanf("%d", &one_x); printf("enter first y coordinate.\n"); printf(">>> \n"); scanf("%d", &one_y); printf("------------------\n"); printf("enter second x coordinate.\n"); printf(">>> \n"); scanf("%d", &two_x); printf("enter second y coordinate.\n"); printf(">>> \n"); scanf("%d", &two_y);
lastly, program solves problem , displays answer.
bottom_number = two_x-one_x; top_number = two_y - one_y; printf ("the slope %d/%d", top_number, bottom_number);
but, whenever run returns strange numbers:
1606415936/1606415768
why this?
i using xcode , #include <stdio.h>
top_number
, bottom_number
declared float
try print them int
(the %d
format specifier tells printf
interpret argument type int
). int
, float
have different sizes , bit representations doesn't work.
there number of options fix this. change them int
int top_number; int bottom_number;
or change format specifiers in final printf
%f
printf ("the slope %f/%f", top_number, bottom_number);
or cast values in printf
printf ("the slope %d/%d", (int)top_number, (int)bottom_number);
note there no benefit in using float
unless may need represent fraction. isn't possible here you're subtracting 2 int
s. calculation of slope (top_number/bottom_number
) should treated float
.
finally, hmjd earlier mentioned, should check return value scanf
make sure have read int
after each call
while (scanf("%d", &one_y) != 1); // repeat pattern each scanf call
Comments
Post a Comment